2013-06-30 66 views
2

美好的一天!使用javascript我試圖創建一個函數,它將創建一個div元素,其觸發按鈕/ div的偏移量很小。好消息是,至少可以創造出儘可能多的元素,並引發其中一種效果。壞消息是,div的XY的樣式無法正常工作。使用x和y偏移另一個元素來定位div元素

該代碼實際上很短,我發佈了一些評論,使其更具可讀性,運行該功能時我沒有得到任何錯誤,所以我真的不知道錯誤在哪裏。

<!DOCTYPE html> 

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta charset="utf-8" /> 
    <title></title> 
    <style> 
     /*What will be created*/ 
     .box { 
      width: 30px; 
      height: 30px; 
      background-color:red; 
      } 

     /*The positioning for the first button*/ 
     .btm12 { 
      margin-left:50%; 
      margin-top:5% 
      } 

     /*The positioning for the second button*/ 
     .btm1 { 
      margin-left:30%; 
      margin-top:10% 
      } 
    </style> 
</head> 
<body> 
    <button id="btn" onclick="createBox()" class="btm1">Click me</button><br /> 
    <button id="btn2" onclick="createBox()" class="btm12">Click me</button> 
</body> 
</html> 
<script> 
    document.getElementById("btn").onclick = function() { createBox(this.id); }; 
    document.getElementById("btn2").onclick = function() { createBox(this.id); }; 

    function createBox(IDI) { 
     //get reference to the element 
     var element = document.getElementById(IDI); 

     //a way we can acces the X and Y coordinates 
     var position = element.getBoundingClientRect(); 
     var x = position.left; 
     var y = position.top; 

     //create, style and set the X/Y of the the div element 
     var box = document.createElement("div"); 
     box.className = "box"; 
     box.style.left = x; 
     box.style.top = y -10; 
     box.style.position = "absolute"; 

     //Apend the element to the body 
     document.body.appendChild(box); 
    } 
</script> 
+0

我會想象它不工作,因爲''

相關問題