缓动动画

缓动动画就是让元素运动速度有所变化,最常见的是让速度慢慢停下来。

思路:

1.让盒子每次移动的距离慢慢变小,速度就会慢慢落下来;

2.核心算法:(目标值-现在的位置)/10 , 作为每次移动的距离步长;

3.停止的条件是: 让当前盒子位置等于目标位置时就停止定时器。

效果:

代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>缓动动画</title>
 6         <style>
 7             *{
 8                 margin: 0;
 9                 padding: 0;
10             }
11             div{
12                 position: absolute;
13                 left: 0;
14                 top: 100px;
15                 width: 100px;
16                 height: 100px;
17                 background-color: yellow;
18             }
19         </style>
20     </head>
21     <body>
22         <div></div>
23         <button>按钮</button>
24         <script>
25             function animate(obj, target){
26                 clearInterval(obj.timer);
27                 obj.timer = setInterval(function(){
28                     //计算步长值
29                     var step = (target - obj.offsetLeft) / 10;
30                     if(obj.offsetLeft >= target){
31                         // 停止动画本质上是停止定时器
32                         clearInterval(obj.timer);
33                     }
34                     obj.style.left = obj.offsetLeft + step + 'px';
35                 },10);
36             }
37             var div = document.querySelector('div');
38             var btn = document.querySelector('button');
39             //调用函数
40 
41             btn.addEventListener('click', function(){
42                 animate(div, 550);
43             });
44         </script>
45     </body>
46 </html>

 

posted on 2020-06-10 22:05  SailorM  阅读(389)  评论(1编辑  收藏  举报