点滴积累【JS】---JS小功能(JS实现匀速运动)

效果:

思路:

利用setInerval()计时器,进行运动。然后关键的一点是在最后停止的时候给它一个填充缝隙的判断。

代码:

 1 <head runat="server">
 2     <title></title>
 3     <style type="text/css">
 4         #div1
 5         {
 6             width: 100px;
 7             height: 100px;
 8             background: #0000FF;
 9             position: absolute;
10             left: 800px;
11             top: 100px;
12         }
13         #div200
14         {
15             width: 1px;
16             height: 400px;
17             background: #FF0000;
18             position: absolute;
19             left: 200px;
20         }
21         #div500
22         {
23             width: 1px;
24             height: 400px;
25             background: #FF0000;
26             position: absolute;
27             left: 500px;
28         }
29     </style>
30     <script type="text/javascript">
31         function move(end) {
32             var oDiv = document.getElementById('div1');
33             var timer = null;
34             timer = setInterval(function () {
35                 var speed = (end - oDiv.offsetLeft) / 5;        //根据终点和offsetLeft取出运动的速度
36                 speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);       //进位取整,小数位变为整位,
37                 //                if (oDiv.offsetLeft <= end) {
38                 //                    clearInterval(timer);
39                 //                }
40                 //                else {
41                 //                    oDiv.style.left = oDiv.offsetLeft + speed + 'px';
42                 //                }
43                 if (Math.abs(end - oDiv.offsetLeft) <= speed) { //由于在停止的时候最后会出现小的缝隙,或者说没有完全的到达指定地点,所以要小于它的速度
44                     clearInterval(timer);                       //当距离小于速度时,让计时器停止
45                     oDiv.style.left = end + 'px';           //在停止后填充缝隙。
46                 }
47                 else {
48                     oDiv.style.left = oDiv.offsetLeft + speed + 'px';       //移动DIV
49                 }
50             }, 30)
51         }
52     </script>
53 </head>
54 <body>
55     <input type="button" id="btn1" value="到500的位置" onclick="move(500);" />
56     <input type="button" id="btn2" value="到200的位置" onclick="move(200);" />
57     <div id="div1">
58     </div>
59     <div id="div200">200
60     </div>
61     <div id="div500">500
62     </div>
63 </body>
原文地址:https://www.cnblogs.com/xinchun/p/3449327.html