<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>缓冲运动</title> <style type="text/css"> #divMove { 100px; height: 100px; position: absolute; top: 200px; left:0px; background: red; } </style> </head> <script type="text/javascript"> window.onload = function() { //获取对象 var oDivMove = document.getElementById("divMove"); var oBtnMove = document.getElementById("btnMove"); oBtnMove.onclick = function() { oDivMove.offsetLeft==0?startMove(oDivMove, 600):startMove(oDivMove, 0);//假设left是0就往右走,否则就往左走 }; }; var oTimer = null; //定时器 function startMove(obj, iTarget) { clearInterval(oTimer); //关闭定时器 oTimer = setInterval(function() { var iSpeed = (iTarget - obj.offsetLeft) / 10; iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);//速度取整数,防止前后波动 if (obj.offsetLeft == iTarget) {//推断是否到达终点 clearInterval(oTimer); //关闭定时器 } else { obj.style.left = obj.offsetLeft + iSpeed + "px";//层运动 document.getElementById("divMove").innerHTML = "速度:"+iSpeed+'</br>'+'距离:'+obj.offsetLeft + "px"; }; }, 30); } </script> <body> <div id="divMove"> </div> <input type="button" id="btnMove" value="開始运动" /> </body> </html>