复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div { position: absolute; left: 0; width: 100px; height: 100px; background-color: #ccc; } span { position: absolute; left: 0; top: 200px; display: block; width: 150px; height: 150px; background-color: purple; } </style> </head> <body> <button>点击2号盒子</button> <div></div> <span>2号盒子 </span> <script> function animate(obj, target) { clearInterval(obj.timer) //清除定时器 避免多次运行 obj.timer = setInterval(function() { //设定定时器 if (obj.offsetLeft >= target) { //判断是否超出目标值 clearInterval(obj.timer); //清除定时器 } else { obj.style.left = obj.offsetLeft + 1 + 'px'; //元素的left 每次加一 } }, 30) //间隔时间 } var div = document.querySelector('div'); // 获取元素 var span = document.querySelector('span'); var btn = document.querySelector('button'); animate(div, 300); btn.addEventListener('click', function() { animate(span, 200); }) </script> </body> </html>
最后
以上就是务实发箍最近收集整理的关于js 动画函数封装的全部内容,更多相关js内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复