匀速运动停止

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

 

posted @ 2013-03-15 11:25  yexingwen  阅读(285)  评论(0编辑  收藏  举报