gpt4 book ai didi

Javascript 在 div createElement 中创建 5 个 img

转载 作者:行者123 更新时间:2023-12-03 07:30:46 25 4
gpt4 key购买 nike

我正在尝试在 div#leftside 内的 5 个不同位置创建 5 个图像。我确实创建了 5 个图像,但它们位于相同的位置,并且不是随机分布在我的 div 内。这是代码...有人可以帮忙吗?

<!DOCTYPE html>
<html lang="en">
<head http-equiv="content-type" content="text/html; charset=utf-8">
<title>Matching game</title>
<style type="text/css">
img {position: absolute;}
div {position: absolute;width: 500px;height: 500px;}
#rightSide { left: 500px;
border-left: 1px solid black }
</style>
<script type="text/javascript">
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var i = 0;
var topvar = (Math.floor(Math.random()*400));
var leftvar = (Math.floor(Math.random()*400));
if (i < 5){
numberOfFaces = document.createElement("img");
i++;
numberOfFaces.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
numberOfFaces.style.top = topvar + 'px';
numberOfFaces.style.left = leftvar + 'px';
theLeftSide.appendChild(numberOfFaces);
}


}
</script>
</head>
<body onload="generateFaces()">
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>

</body>
</html>

最佳答案

当您打算使用 while 循环时,您使用了 if 语句。此外,您需要将定位逻辑移至循环中。

https://jsfiddle.net/knwL2bn4/

重构:

    <!DOCTYPE html>
<html lang="en">
<head http-equiv="content-type" content="text/html; charset=utf-8">
<title>Matching game</title>
<style type="text/css">
img {position: absolute;}
div {position: absolute;width: 500px;height: 500px;}
#rightSide { left: 500px;
border-left: 1px solid black }
</style>
<script type="text/javascript">
function generateFaces() {
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var i = 0;

while (i < 5){
var topvar = (Math.floor(Math.random()*400));
var leftvar = (Math.floor(Math.random()*400));
numberOfFaces = document.createElement("img");
i++;
numberOfFaces.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
numberOfFaces.style.top = topvar + 'px';
numberOfFaces.style.left = leftvar + 'px';
theLeftSide.appendChild(numberOfFaces);
}


}
</script>
</head>
<body onload="generateFaces()">
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>

</body>
</html>

关于Javascript 在 div createElement 中创建 5 个 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35807390/

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