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

javascript动画效果之匀速运动(修订版)

2016-11-02 17:19 309 查看

 

在编写多块同时触发运动的时候,发现一个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为pto.offsetLeft需要达到的距离
17                     showPto(0);
18                 }
19                 //同理
20             btn.onmouseleave = function() {
21                 //同理
22                 showPto(-200);
23             }
24
25             //自定义函数,one为自定义参数
26             function showPto(one) {
27                 //当前只需要一个定时器,所以需要在每次开始前清除定时器
28                 clearInterval(timer);
29                 //定义一个名为timer的定时器
30                 timer = setInterval(function() {
31                     if (one > pto.offsetLeft) {
32                         //当0>pto.offsetLet时,pto需要被显示,所以speed为正值
33                         speed = 10;
34                     } else {
35                         //同理,需要被隐藏时,speed为负值
36                         speed = -10;
37                     }
38                     if (pto.offsetLeft == one) {
39                         //当pto的值达到0或者-200时候就达到需求了,需要停止定时器,
40                         clearInterval(timer);
41                     } else {
42                         //没有到0或者-200时候,就需要通过speed来自增或自减
43                         pto.style.left = pto.offsetLeft + speed + 'px';
44                     }
45
46                 }, 30);
47             }
48         }
49 </script>

 

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