动画函数封装

核心原理:

通过定时器 setInterval() 不断移动盒子。

动画原理:

1.获得盒子当前位置;

2.让盒子在当前位置加上1个移动距离;

3.利用定时器不断重复这个操作;

4.加一个阶数定时器的条件;

5.注意此元素需要添加定位,才能使用element.style.left。

效果:

代码:

 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                 width: 100px;
15                 height: 100px;
16                 background-color: yellow;
17             }
18             span{
19                 position: absolute;
20                 left: 20px;
21                 top: 150px;
22                 display: block;
23                 width: 100px;
24                 height: 50px;
25                 background-color: rgb(182, 182, 231);
26                 line-height: 50px;
27             }
28         </style>
29     </head>
30     <body>
31         <div></div>
32         <span>HiHiHiHi</span>
33         <button>按钮</button>
34         <script>
35             // 简单封装函数 需要传递2个参数,动画对象和移动到的距离
36             function animate(obj, target){
37                 // 当不断点击按钮,这个元素的速度会越来越快,因为开启了太多定时器
38                 // 解决方案是 让我们元素只有一个定时器执行,先清楚以前的定时器,只保留当前一个定时器执行
39                 clearInterval(obj.timer);
40                 obj.timer = setInterval(function(){
41                     if(obj.offsetLeft >= target){
42                         // 停止动画本质上是停止定时器
43                         clearInterval(obj.timer);
44                     }
45                     obj.style.left = obj.offsetLeft + 1 + 'px';
46                 },10);
47             }
48             var div = document.querySelector('div');
49             var span = document.querySelector('span');
50             var btn = document.querySelector('button');
51             //调用函数
52             animate(div, 400);
53             btn.addEventListener('click', function(){
54                 animate(span, 550)
55             });
56         </script>
57     </body>
58 </html>

 

posted on 2020-06-05 21:17  SailorM  阅读(207)  评论(0编辑  收藏  举报