2016-06-10 5 views
0

코드는 하나씩 5 개의 요소를 생성하여 페이지가 다운로드 될 때마다 무작위로 5 개의 요소 (newFace)를 보게됩니다.왜 요소가 임의의 위치에 나타나지 않지만 div의 꼭대기에 정렬 상태로 유지됩니까?

이 코드는 모두 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

은 "leftSide"위치에 상대적으로 위치하고 있습니다. – JonSG

+0

leftSide와 img는 모두 css에서 절대 위치에 있습니다. (작업에 절대 위치가 있어야 함) –

+0

[실행 스택 스 니펫]을 만들 수 있습니까? (http://meta.stackoverflow.com/questions/270944/feedback- requested-stack-snippets-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>