[英]Adding an image multiple times in JavaScript
我被MOOC卡住了。 指令如下:“在此函數中,在循環中創建面。該循環執行numberOfFaces次。在每次迭代中”
應該在左側顯示五個面孔。 但是,我只能得到一個。
在下面可以找到我的代碼。 請告訴我我做錯了/如何解決。
<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>
干杯,J
這里正在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>
編輯:發現實際問題:)
作者正在應用div, img {position: absolute}
樣式,並在top
<div>
而不是每個<img>
處分別對top
, left
值進行簽名。
此修復問題:
smilies.style.top = top_position + "px";
smilies.style.left = left_position + "px";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.