2016-06-10 26 views
0

代码应该一个一个地生成5个元素,这样当下载页面时,我们将在随机地方看到5个元素(newFace)。为什么这些元素没有出现在随机的地方,但他们保持对齐的顶部?

此代码生成的所有5个元素,但他们是住一个对齐,而不是在随机位置出现如希望

function generate_faces() { 
    var theLeftSide = document.getElementById("leftSide"); 
    var number_of_faces = 0; 
    while (number_of_faces < 5){ 
     var top_position = Math.floor(Math.random()*300); 
     var left_position = Math.floor(Math.random()*300); 
     newFace = document.createElement("img"); 
     newFace.setAttribute(
      "src", 
      "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png" 
     ); 
     newFace.style.top = top_position+"px"; 
     newFace.style.left = left_position+"px"; 
     theLeftSide.appendChild(newFace); 
     number_of_faces = number_of_faces + 1; 
    } 
} 
+0

是“left side”定位的相对位置,img绝对有些地方? – JonSG

+0

leftSide和img都在css中绝对定位(任务告诉他们必须具有position:absolute) –

+0

您可以制作一个[可执行的Stack Snippet](http://meta.stackoverflow.com/questions/270944/feedback-请求堆栈片段-2-0),证明了这个问题? – Barmar

回答

0

试试这一个。

<!DOCTYPE html> 
<html> 
<head></head> 
<style> 
html, body, leftSide { 
    width: 100%; 
    height: 100%; 
    position: relative; 
} 
#leftSide { 
    position: relative; 
} 

#leftSide img { 
    position: absolute; 
} 
</style> 
<body onclick="generate_faces()"> 
<div id="leftSide"> 

</div> 
</body> 
</html> 
<script> 
function generate_faces() { 

var theLeftSide = document.getElementById("leftSide"); 
var number_of_faces = 0; 
while (number_of_faces < 5){ 
    var top_position = Math.floor(Math.random()*300); 
    var left_position = Math.floor(Math.random()*300); 
    newFace = document.createElement("img"); 
    newFace.setAttribute(
     "src", 
     "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png" 
    ); 
    newFace.style.top = top_position+"px"; 
    newFace.style.left = left_position+"px"; 
    theLeftSide.appendChild(newFace); 
    number_of_faces = number_of_faces + 1; 
    } 
} 
</script> 
相关问题