javascript 小方块平移

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9 </head>
10 
11 <body>
12     <div class="box" style="100px; height:100px; background-color:red; position:absolute; top: 0; left: 0;">
13         <!--要移动的小盒子-->
14     </div>
15     <button style="position:absolute; top:200px;">
16         开始
17     </button>
18 
19     <script>
20         var div = document.getElementsByClassName("box")[0];//选择要移动的盒子
21         var btn = document.getElementsByTagName("button")[0];
22       
23         var timer = null;
24         btn.onclick = function () {//在按钮上绑定点击事件,点击按钮,盒子开始移动
25             var speed = 5;
26             clearInterval(timer);//每次运行的时候,先把上一个定时器给停止了,不然同个时间段会执行多次,会导致速度越来越快
27 
28             timer = setInterval(function () {//每次执行都会把唯一标识返回到timer 想要停止就得清除唯一标识
29 
30                 div.style.left = div.offsetLeft + speed + "px";
31                 //获取当前盒子的 left 加上我们设置的速度 加上 px 再赋给 小盒子
32             }, 50)//每50毫秒执行一次
33         }
34 
35     </script>
36 </body>
37 
38 </html>

升级版

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>Document</title>
 9 </head>
10 
11 <body>
12     <div class="box" style="100px; height:100px; background-color:red; position:absolute; top: 0; left: 1400px;">
13                                                                                                 <!-- Left设置小盒子在右边 -->
14     </div>
15     <button style="position:absolute; top:200px;">
16         开始
17     </button>
18 
19     <span style="position:absolute; left:700px; top:0; height:100px; 0; border:1px solid black;"></span>
20 
21     <script>
22         var div = document.getElementsByClassName("box")[0];
23         var btn = document.getElementsByTagName("button")[0]; 
24         var span = document.getElementsByTagName('span')[0];
25         var timer = null; //定时器的唯一标识
26         btn.onclick = function () {
27 
28            UniformMotion(div, 700)
29         }
30 
31 
32         function UniformMotion(dom , target){ //第一个参数,要运动的dom,第二个要停止的位置
33             var speed = target - dom.offsetLeft > 0 ? 7 : -7; //判断要运动的盒子在左边还是在右边
34 
35             timer = setInterval(function () { 
36                 if (Math.abs(target - dom.offsetLeft) < Math.abs(speed)) { 
37                     clearInterval(timer);
38                     dom.style.left = target + "px";
39                 }else{
40                     dom.style.left = dom.offsetLeft + speed + "px";
41                 }
42                 
43             }, 50)
44         }
45     </script>
46 </body>
47 
48 </html>

 

原文地址:https://www.cnblogs.com/yanggeng/p/10553937.html