代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id='box'></div> <script> var oBox = document.getElementById("box"); var maxLeft = utils.win('clientWidth')-oBox.offsetWidth; var step = 5; var timer = null; //使用递归思想完成setTimeout的轮循动画:每一次在执行动画之前把上一次设置没用的定时器清除掉,节约我们的内存空间 function move(){ window.clearTimeout(timer); var curLeft = utils.css(oBox,"left"); if(curLeft+step >= maxLeft){//边界判断 utils.css(oBox,"left",maxLeft); return; } curLeft+=step; utils.css(oBox,"left",curLeft); timer = window.setTimeout(move,10) } move(); </script> </body> </html>