JS 缓动动画封装函数

可保存在js中,在html页面引入使用.

例如保存在 animate.js

 1 <html>
 2   <head>
 3     <script src='animate.js'></script>
 4   </head>
 5   <body>
 6     <script>
 7       animation(obj,target,callback)
 8     </script>
 9   </body>
10 </html>

animate.js

 1 function animation(obj, target,callback) {
 2 
 3     //让定时器唯一
 4     clearInterval(obj.timer)
 5     
 6     obj.timer = setInterval(function () {
 7         
 8         var step = (target - obj.offsetLeft) / 10
 9         //算元运算判断,如果步长值>0 就向上取整,否则就向下取整
10         step = step > 0 ? Math.ceil(step) : Math.floor(step)
11 
12         if (obj.offsetLeft == target) {
13             clearInterval(obj.timer)
14 
15             //判断是否有回调函数
16             // if(callback){
17             //     callback()
18             // }
19 
20             // 短路运算
21             //如果有传入参数,就执行callback()
22             //若没有,则返回
23             callback && callback()
24         }
25         obj.style.left = obj.offsetLeft + step + 'px'
26     },5)
27 }
时间若流水,恍惚间逝去
原文地址:https://www.cnblogs.com/alanshreck/p/14276189.html