具体代码如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin:0; padding:0; } #box{ position:absolute; top:0; left:0; padding:0; width:100px; height:100px; background:lightblue; } </style> </head> <body> <div id='box'></div> <script> //思想1: var oBox = document.getElementById('box'); //实现一个匀速运动:在指定时间内完成动画:计算出总距离/总时间,然后求出对应的步长(每10ms走一步的话需要走多远) var maxLeft = (document.documentElement.clientWidth || document.body.clientWidth) - oBox.offsetWidth; var duration = 2000; var step = (maxLeft/duration)*10; var timer = window.setInterval(function(){ var curLeft = utils.css(oBox,"left"); curLeft+=step; if(curLeft>=maxLeft){ window.clearInterval(timer); return; } utils.css(oBox,"left",curLeft); },10) //思想2: function Linear(t,b,c,d){//相对应的是time begin change duration return c*t/d+b } var oBox = document.getElementById('box'); var target = (document.documentElement.clientWidth || document.body.clientWidth) - oBox.offsetWidth; var begin = utils.css(oBox,'left'),change = target-begin; var duration = 2000,time = null; var timer = window.setInterval(function(){ time+=10; if(time>=duration){ utils.css(oBox,"left",target); window.clearInterval(timer); return; } var curPos = Linear(time,begin,change,duration); utils.css(oBox,"left",curPos) },10) </script> </body> </html>