缓动动画多个目标值之间移动

效果:

代码:

 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 class="btn1">点击到500</button>
24         <button class="btn2">点击到800</button>
25         <script>
26             function animate(obj, target){
27                 clearInterval(obj.timer);
28                 obj.timer = setInterval(function(){
29                     //计算步长值
30                     //把步长值改成整数,不要出现小数问题
31                     var step = (target - obj.offsetLeft) / 10;
32                     step = step > 0 ? Math.ceil(step) : Math.floor(step);
33                     if(obj.offsetLeft == target){
34                         // 停止动画本质上是停止定时器
35                         clearInterval(obj.timer);
36                     }
37                     obj.style.left = obj.offsetLeft + step + 'px';
38                 },10);
39             }
40             var div = document.querySelector('div');
41             var btn1 = document.querySelector('.btn1');
42             var btn2 = document.querySelector('.btn2');
43             //调用函数
44 
45             btn1.addEventListener('click', function(){
46                 animate(div, 500);
47             });
48             btn2.addEventListener('click', function(){
49                 animate(div, 800);
50             });
51         </script>
52     </body>
53 </html>

 

posted on 2020-06-11 10:16  SailorM  阅读(256)  评论(0编辑  收藏  举报