1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style> 7 #div1{width: 100px; height: 100px;background-color:red;position: absolute; 8 left: 300px;top: 50px;} 9 10 #div2{width: 1px; height: 300px;background-color:black;position: absolute; 11 left: 100px;top: 0px;} 12 #div3{width: 1px; height: 300px;background-color:black;position: absolute; 13 left: 300px;top: 0px;} 14 </style> 15 <script> 16 var timer=null; 17 function startMove(iTarget){ 18 var oDiv=document.getElementById('div1'); 19 clearInterval(timer); 20 timer=setInterval(function(){ 21 var speed=0; 22 if(oDiv.offsetLeft<iTarget){ 23 speed=7; 24 } 25 else{ 26 speed=-7; 27 } 28 if(Math.abs(iTarget-oDiv.offsetLeft)<=7){ 29 clearInterval(timer); 30 31 oDiv.style.left=iTarget+'px'; 32 } 33 else{ 34 oDiv.style.left=oDiv.offsetLeft+speed+'px'; 35 } 36 },30) 37 } 38 </script> 39 </head> 40 <body> 41 <input type="button" value="到100" onclick="startMove(100)" /> 42 <input type="button" value="到300" onclick="startMove(300)" /> 43 <div id="div1"> 44 </div> 45 <div id="div2"> 46 </div> 47 <div id="div3"> 48 </div> 49 </body> 50 </html>