gpt4 book ai didi

javascript - 在 JavaScript 中多次添加图像

转载 作者:行者123 更新时间:2023-11-30 16:18:39 25 4
gpt4 key购买 nike

我被困在 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>

enter image description here

编辑:发现实际问题:)

作者正在申请 div, img {position: absolute}款式、签名top , left while 外部的值 <div> , 而不是每个 <img> .

这修复了问题:

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

Final Plunk

关于javascript - 在 JavaScript 中多次添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35091376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com