我有一个名为 index.html 的 html 文件,里面有这个 div
<body>
<div id="rock"> <img src="rock.PNG" alt="rock" onclick="test()"> </div>
<div id="paper"> <img src="paper.PNG" alt="rock"></div>
<div id="scissors"> <img src="scissors.PNG" alt="rock"> </div>
test 是我的函数,它在同一个文件中并写在这里
<script type="text/javascript">
function test(){
var elem = document.getElementById("rock");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
但是当我的页面运行时,我单击图像,它并没有移动。图像已显示,并且 onclick 确实有效(我在警报下对其进行了测试)但图像不会移动...有什么想法吗?
最佳答案
您需要指定 position
属性,可能是 relative
。您也可以使用 absolute
或 fixed
定位,如果其中之一更符合您的需求的话。
#rock, #paper, #scissors {
position: relative;
}
关于javascript - 单击图像时移动图像的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56046197/