天天看點

第57天:勻速運動封裝函數

一、動畫的原理

 動畫的基本原理 : 讓盒子的 offsetLeft   +  步長

Math.abs(-5)   取絕對值函數

二、勻速運動封裝函數

1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>勻速動畫封裝</title>
 6     <style>
 7         div{
 8             width: 100px;
 9             height: 100px;
10             background-color: yellow;
11             position: absolute;
12         }
13     </style>
14 </head>
15 <body>
16 <button id="btn1">200</button>
17 <button id="btn2">400</button>
18 <div id="box"></div>
19 </body>
20 </html>
21 <script>
22     var btn1=document.getElementById("btn1");
23     var btn2=document.getElementById("btn2");
24     var box=document.getElementById("box");
25     btn1.onclick=function(){
26         animate(box,200);
27     }
28     btn2.onclick=function(){
29         animate(box,400);
30     }
31     //封裝勻速運動
32     function animate(obj,target){
33         var speed=obj.offsetLeft < target ? 5 : -5;//用來判斷是+還是-
34         obj.timer=setInterval(function(){
35             var result=target-obj.offsetLeft;//內插補點不會大于5
36             obj.style.left=obj.offsetLeft+speed+"px";
37             if(Math.abs(result)<=5){//如果內插補點不小于5 到位置了
38                 clearInterval(obj.timer);
39                 obj.style.left=target+"px";//有5px差距直接跳轉
40             }
41         },20)
42     }
43 </script>      

繼續閱讀