我正在尝试在屏幕上移动图像,并在到达屏幕边缘时将其重置回起始位置。我已经/已经完成了动画部分的工作,但在窗口边框上挣扎。
我的 moveDown(( 函数按我的预期工作,但是当将代码复制到 moveRight(( 函数时,它会将图像移动到十个像素以上,重置并陷入重复相同移动的循环中。
提前感谢您的帮助,我很想听听有关如何清理此代码或使其更加优化的任何想法。
<script type = "text/javascript">
<!--
var imgObj = null;
var animate ;
var maxw = window.outerWidth + "px";
var maxh = window.innerHeight + "px";
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
imgObj.style.top = '0px';
}
function moveRight() {
if (imgObj.style.left > maxw) {
imgObj.style.left = "0px";
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20);
} else{
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20);
document.getElementById("test").innerHTML = maxw;
document.getElementById("test2").innerHTML = imgObj.style.left;
}
}
function moveDown() {
if (imgObj.style.top > maxh) {
imgObj.style.top = '0px';
imgObj.style.top = parseInt(imgObj.style.top) + 10 + 'px';
animate = setTimeout(moveDown,20);
} else{
imgObj.style.top = parseInt(imgObj.style.top) + 10 + 'px';
animate = setTimeout(moveDown,20); // call moveDown in 20msec
}
}
function stop() {
location.reload();
}
window.onload = init;
//-->
</script>
我认为moveDown
也坏了,但你没有注意到。
imgObj.style.left
和maxw
都是字符串。"11px"
大于"1000px"
。 也许maxh
恰好是一个有效的值,但maxw
不是。
解决方案相当简单:使用parseInt
并作为数字进行比较。
您还可以使用 Element.getBoundingClientRect(( 来避免从style
获取值。请记住,访问getBoundingClientRect
会触发重绘,这可能会使动画断断续续,从这个意义上说,它并不比访问.style
更好。