如果我取出变量计数器并将 document.getElementById("movee").style.top
设置为一个数字,它就可以正常工作。结合变量计数器和那段代码理论上可以使图像移动。但由于某种原因它无法正常工作!
<html>
<style type="text/css">
#movee
{
position:absolute;
}
</style>
<script type="text/javascript">
function goDown()
{
var counter=1;
while (counter<300)
{
document.getElementById("movee").style.top="counter";
var counter=counter+1;
}
}
</script>
<input type="button" onclick="goDown()" value="Move!">
<img src="test.png" id="movee"></img>
</html>
最佳答案
您将 #movee 的顶部样式属性设置为字符串“counter”,而不是变量 counter 的值
document.getElementById("movee").style.top=counter+"px";
此外,您似乎正在尝试为元素设置动画,您的技术将不起作用,因为更新只会在您的脚本完成运行后发生。我建议研究 css 转换,或者像 jQuery(jQuery.animate) 这样的动画库。
关于javascript - 设置 HTML 元素的垂直位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15044617/