我试图将微笑图像放在左侧 div 的随机位置。但图像不是随机出现的,而是连续显示图像。为什么会这样?
<html>
<head>
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id= "leftSide"></div>
<div id = "rightSide"></div>
<style>
img1 {position:absolute}
div {position:absolute; width:500px;height: 500px}
#rightSide {left:500px;border-left: 1px solid black}
</style>
<script>
var numberOfFaces =5,i;
var theLeftSide = document.getElementById("leftSide");
function generateFaces()
{
for( i=0;i<numberOfFaces;i++)
{
var img1 =document.createElement("img");
img1.src = "smile.png";
var topran = Math.random() * 400;
var topran = Math.floor(topran);
var leftran = Math.random() *400;
var leftran = Math.floor(leftran);
img1.style.top = topran + "px";
img1.style.left = leftran + "px";
theLeftSide.appendChild(img1);
}
}
</script>
</head>
<body onload = "generateFaces()">
</body>
</html>
最佳答案
您不能在 CSS 中使用 img1 {position:absolute}
来设置微笑图像的样式。将您的 CSS 更改为 .smile {position:absolute}
(类选择器)并在 img1
上设置类 smile
。
var img1 =document.createElement("img");
img1.src = "smile.png";
img1.className = "smile";
关于javascript图像位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895150/