您的位置:首页 > Web前端 > JavaScript

javascript动画效果之缓冲动画(修改版)

2016-11-02 21:12 357 查看

在编写多块同时触发运动的时候,发现一个BUG,

timer = setInterval(show, 30);本来show是一个自定义函数,
当设为timer = setInterval(show(one,two), 30);时,发现show里面的参数one和two无法被导入,所以需要做以下代码改进和优化

原版的html和css代码在这里javascript动画效果之缓冲动画

js代码如下

1  <script>
2         function $(id) {
3             return typeof id === "string" ? document.getElementById(id) : id;
4         }
5
6         window.onload = function() {
7
8             //自定义变量
9             var pto = $("div");
10             var btn = $("show");
11             var timer = null;
12             var speed = 0;
13
14             //鼠标移动进入绑定事件
15             btn.onmouseenter = function() {
16                 //调用自定义函数,并传入参数0
17                 showPto(0);
18             }
19             //鼠标移动离开绑定事件
20             btn.onmouseleave = function() {
21                 //同理,并传入参数-200
22                 showPto(-200);
23             }
24
25             //自定义函数,自定义参数名
26             function showPto(obj) {
27                 //当前只需要一个定时器,所以需要在每次开始前清除定时器
28                 clearInterval(timer);
29                 //定义定时器,自动增减
30                 timer = setInterval(function() {
31                     //obj为0时(0--200)/20,speed为+10,Math.ceil(),此时pto.offsetLeft变0
32                     //onj为-200时(-200-0)/20,speed为-10,所以Math.floor()
33                     speed = (obj - pto.offsetLeft) / 20;
34                     speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
35                     if (pto.offsetLeft == obj) {
36                         //当pto.offsetLeft为0或者-200时,清除定时器
37                         clearInterval(timer);
38                     } else {
39                         //通过speed来增加减少offsetLeft的值
40                         pto.style.left = pto.offsetLeft + speed + 'px';
41                     }
42                 }, 30);
43             }
44
45
46
47         }
48     </script>

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: