<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> #demo{ 100px; height:100px; background-color: pink; position:absolute; top:30px; left:0; } #demo2{ 200px; height:200px; background-color: green; position: absolute; left:0; top:200px; } </style> </head> <body> <button id="btn300">300</button> <button id="btn600">600</button> <div id="demo"></div> <div id="demo2"></div> </body> </html> <script> function $id(id){return document.getElementById(id);} var timer=null; $id("btn300").onclick=function (){ run($id("demo"),300); run($id("demo2"),600); } $id("btn600").onclick=function () { run($id("demo"),600); run($id("demo2"),300); } function run(obj,target) { var speed=(target-obj.offsetLeft)>0 ? 10 : -10; //用来判断应该往前走还是后退 clearInterval(obj.timer); obj.timer=setInterval(function(){ var result=target-obj.offsetLeft; //盒子距离目标位置的距离 if(Math.abs(result)<=10) //盒子距离目标位置的距离在步长10以内时,说明到位置了,因为不会在10以内 { obj.style.left=target+"px"; clearInterval(obj.timer); } else{ obj.style.left=obj.offsetLeft+speed+"px"; } },10) } </script>