动画函数的使用

原理图:

 

效果图:

JS代码:

 1 function animate(obj, target, callback){
 2     clearInterval(obj.timer);
 3     obj.timer = setInterval(function(){
 4         //计算步长值
 5         //把步长值改成整数,不要出现小数问题
 6         var step = (target - obj.offsetLeft) / 10;
 7         step = step > 0 ? Math.ceil(step) : Math.floor(step);
 8         if(obj.offsetLeft == target){
 9             // 停止动画本质上是停止定时器
10             clearInterval(obj.timer);
11             if(callback){
12                 //调用函数
13                 callback();
14             }
15         }
16         obj.style.left = obj.offsetLeft + step + 'px';
17     },10);
18 }

HTML代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>引用animate动画函数</title>
 6         <script src="animate.js"></script>
 7         <style>
 8             .sliderbar{
 9                 position: fixed;
10                 right: 0;
11                 bottom: 100px;
12                 width: 40px;
13                 height: 40px;
14                 text-align: center;
15                 line-height: 40px;
16                 cursor: pointer;
17                 color: #fff;
18             }
19             .con{
20                 position: absolute;
21                 left: 0;
22                 top: 0;
23                 width: 200px;
24                 height: 40px;
25                 background-color: gray;
26                 z-index: -1;
27             }
28         </style>
29     </head>
30     <body>
31         <div class="sliderbar">
32             <span>←</span>
33             <div class="con">问题反馈</div>
34         </div>
35         <script>
36             // 1.获取元素
37             var sliderbar = document.querySelector('.sliderbar');
38             var con = document.querySelector('.con');
39             var span = document.querySelector('span');
40             // 当我们鼠标经过sliderbar就会让con这个盒子滑动到左侧
41             // 当我们鼠标离开sliderbar就会让con这个盒子滑动到右侧
42             sliderbar.addEventListener('mouseenter',function(){
43                 // animate(obj, target, callback)
44                 animate(con, -160, function(){
45                     // 当动画执行完毕,更改箭头方向
46                     span.innerHTML = '→';     // 或者直接sliderbar.children[0].innerHTML ='';
47                 });
48             })
49             sliderbar.addEventListener('mouseleave',function(){
50                 animate(con, 0, function(){
51                     span.innerHTML = '←';
52                 });
53             })
54         </script>
55     </body>
56 </html>

 

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