function dr(){ var img = document.getElementById("img"); var MX = img.style.left; if (MX<936) { MX++; img.style.left = -MX +"px"; } if(MX>936){ MX--; img.style.left = MX +"px"; } var g = setTimeout("dr()",10); } window.onload = function(){ dr(); }
谁能明白其内在的原因,MX并没有因为setTimeout而自加到936或者自减到936.
我在游览器中实际测试过,实际上,它只执行了一次,也就是-1px;
var MX = img.style.left;
取出的结果不是整数,含有px
改成var MX = img.offsetLeft;
(function(){ function dr(){ var img = document.getElementById("img"); //var MX = img.offsetLeft; var MX = parseInt(img.style.left); if (MX<936) { MX--; } if(MX>936){ MX++; } if (MX==936||MX==(-936)) { return true; } img.style.left = MX +"px"; setTimeout(dr,10); } function de(){ var img = document.getElementById("img"); img.style.position = "absolute"; img.style.top = "0px"; img.style.left = "0px"; setTimeout(dr,10); } window.onload = function(){ de(); } })();
我重新写了一下,现在可以了,不过也谢谢你~