在JavaScript中多次添加图像

时间:2016-01-29 18:19:03

标签: javascript

我被困在MOOC的练习中。说明如下: "在此功能中,面是循环创建的。循环执行numberOfFaces次。在每次迭代中#34;

应该在左侧显示五张脸。但是,我只得到一个。

您可以在下面找到我的代码。请告诉我我做错了什么/如何解决它。



<html>
<head>
    <title>Matching Game</title>
    <style>
        img {position: absolute}
        div {width: 500px; height: 500px; position: absolute}
        #rightSide {left: 500px; border-left: 1px solid black}
    </style>
</head>
    <body id = "theBody" onload = "generateFaces()">
        <h1 id = "title">Matching Game</h1>
        <p id = "instructions"><b>Intructions:</b><br>
        Click on the extra smiling face on the left.
        Watch out though! If you click on the wrong place, it will be "Game Over"!</p>
        
        <div id = "leftSide"></div>
        <div id = "rightSide"></div>
        
        <script>
        var numberOfFaces = 5;
        var theLeftSide = document.getElementById("leftSide");

        function generateFaces() {
            for(i = 0; i < numberOfFaces; i++) {
                var smilies = document.createElement("img");
                smilies.src = "https://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
                
                var top_position = Math.random() * 400;
                top_position = Math.floor(top_position);
                var left_position = Math.random() * 400;
                left_position = Math.floor(left_position);
                
                theLeftSide.style.top = top_position + "px";
                theLeftSide.style.left = left_position + "px";
                theLeftSide.appendChild(smilies);
            }
            
        }
        
        </script>
    </body>
</html>
&#13;
&#13;
&#13;

干杯, Ĵ

1 个答案:

答案 0 :(得分:2)

这是有效的Plunker

您的代码段很好。这是完整的事情:

 <html>
   <body>
     <div id="leftSide"></div>


     <script>
        var numberOfFaces = 5;
        var theLeftSide = document.getElementById("leftSide");
        generateFaces()
        function generateFaces() { // I need to fix this function. Something is wrong.
          for(i = 0; i < numberOfFaces; i++) {
            var smilies = document.createElement("img");
            smilies.src = "https://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";

            var top_position = Math.random() * 400;
            top_position = Math.floor(top_position);
            var left_position = Math.random() * 400;
            left_position = Math.floor(left_position);

            theLeftSide.style.top = top_position + "px";
            theLeftSide.style.left = left_position + "px";
            theLeftSide.appendChild(smilies);
          }
        }
     </script>
   </body>
 </html>

enter image description here

编辑:发现实际问题:)

作者正在应用div, img {position: absolute}样式,并在外top时签署left<div>值,而不是每个<img>

这解决了问题:

smilies.style.top = top_position + "px";
smilies.style.left = left_position + "px";

Final Plunk