天天看點

第59天:緩動動畫封裝函數

一、三個取整函數

 這三個函數都是  數學函數   

 Math   

 Math.ceil()    向上取整      天花闆    

 比如說  console.log(Math.ceil(1.01))       結果 是 2  

         console.log(Math.ceil(1.9))        結果 2

         console.log(Math.ceil(-1.3))       結果 是  -1   

 Math.floor()   向下取整      地闆  

    比如說 console.log(Math.floor(1.01))       結果 是 1  

         console.log(Math.floor(1.9))           結果 1

         console.log(Math.floor(-1.3))       結果 是  -2   

 Math.round()   四舍五入函數   

            console.log(Math.round(1.01))       結果 是 1

           console.log(Math.round(1.9))       結果 是 2

二、緩動動畫原理

  勻速動畫的原理:   盒子本身的位置  +  步長  

  緩動動畫的原理:    盒子本身的位置  +  步長 (不斷變化的)

三、緩動動畫封裝函數如下:

1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         div {
 8             width: 100px;
 9             height: 100px;
10             background-color: pink;
11             position: absolute;
12             left: 0;
13             opacity: 0.3;
14         }
15     </style>
16 </head>
17 <body>
18 <button id="btn200">200</button>
19 <button id="btn400">400</button>
20 <div id="box"></div>
21 </body>
22 </html>
23 <script>
24     var btn200 = document.getElementById("btn200");
25     var btn400 = document.getElementById("btn400");
26     var box = document.getElementById("box");
27     btn200.onclick = function() {
28         animate(box,200);
29     }
30     btn400.onclick = function() {
31         animate(box,400);
32     }
33 
34     function animate(obj,target){  //  第一個參數 動誰   第二個參數  動多少
35         clearInterval(obj.timer);
36         obj.timer = setInterval(function() {
37               // 計算步長   動畫的原理    盒子本身的位置  +  步長
38               var step = (target - obj.offsetLeft) / 10;  // 步長
39               step =  step > 0 ? Math.ceil(step) : Math.floor(step);  //  取整步長
40               // obj.style.left = 盒子本身的位置  +  步長
41               obj.style.left = obj.offsetLeft + step + "px";
42               if(obj.offsetLeft == target){
43                   clearInterval(obj.timer);
44               }
45         },30)
46     }
47  </script>

      

繼續閱讀