gpt4 book ai didi

javascript - appendChild 删除样式

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:52 25 4
gpt4 key购买 nike

我尝试使用 appendChild 函数来创建具有某些样式属性的新图像节点。使用后,所有属性都会消失。图片本应随机放置在左侧 div 上,但实际上它们是对齐排列的。

<html>
<head>
<title>Matching Game</title>
<style>
#rightSide {
position: absolute;
left: 700px;
border-left: 1px solid black;
width:700px;
height:700px;
}

#leftSide {
width:700px;
height:700px;
position: absolute;

}

</style>
</head>



<body onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>

<div id='leftSide'>

</div>

<div id='rightSide'>

</div>

<script>
var numberOfFaces = 5;
var theLeftSide = document.getElementById('leftSide');


var generateFaces = function() {
for(var i = 0; i < numberOfFaces; i++)
{
var img = document.createElement('img');
img.src = 'smile.png';
img.style.top = Math.floor(Math.random()*600);
img.style.left = Math.floor(Math.random()*600);
theLeftSide.appendChild(img);
}
}
</script>
</body>


</html>

http://i.stack.imgur.com/fZaYA.png

最佳答案

Math.floor(Math.random()*600); 将返回一个数字。除非值为 0,否则 CSS lefttop 属性需要一个 length。长度有单位。

此外,您还没有将 position 属性从 static 更改为其他属性,因此 lefttop属性将无效,因为它们仅适用于定位元素。

关于javascript - appendChild 删除样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35420023/

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