javascript动画效果之缓冲动画

这里的html和css的代码是复制之前的随便匀速运动的,所以不需要改变

 1 <!DOCTYPE html>
 2 <html>
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>Document</title>
 7     <style type="text/css">
 8         * {
 9             margin: 0;
10             padding: 0;
11             font-size: 12px;
12         }
13         
14         div {
15             width: 200px;
16             height: 200px;
17             background: green;
18             position: relative;
19             left: -200px;
20         }
21         
22         span {
23             width: 30px;
24             height: 30px;
25             line-height: 30px;
26             background: red;
27             position: absolute;
28             left: 200px;
29             top: 85px;
30             text-align: center;
31             cursor: pointer;
32         }
33     </style>
34 </head>
35 
36 
37 
38 
39 <body>
40 <div id="div">
41     <span id="show">show</span>
42 </div>
43 </body>
44 
45 </html>

js代码和之前的匀速运动的区别在于需要添加一个变量用来控制速度变化

 1 <script>
 2     function $(id) {
 3         return typeof id === "string" ? document.getElementById(id) : id;
 4     }
 5 
 6     window.onload = function() {
 7         //变量定义区
 8         var pto = $("div");
 9         var btn = $("show");
10         var timer = null;
11         var speed = 0;
12 
13         //鼠标移动绑定事件
14         btn.onmouseenter = start;
15 
16         //函数用于调用定时器timer
17         function start() {
18             clearInterval(timer);
19             timer = setInterval(show, 30);
20         }
21 
22         //函数用于自动增加
23         function show() {
24             //speed是速度变量,用于控制窗口移动的速度
25             //这里的/20可以变为除任何数,主要为控制速度变化
26             speed = (0 - pto.offsetLeft) / 20;
27             //调用了Math方法,ceil是四舍五入取整
28             speed = Math.ceil(speed);
29             if (pto.offsetLeft == 0) {
30                 clearInterval(timer);
31             } else {
32                 pto.style.left = pto.offsetLeft + speed + 'px';
33             }
34 
35         }
36 
37         //鼠标移出绑定事件
38         btn.onmouseleave = back;
39 
40         //函数用于调用定时器timer
41         function back() {
42             clearInterval(timer);
43             timer = setInterval(clear, 30);
44         }
45 
46         //函数用于自动减少
47         function clear() {
48             speed = (-200 - pto.offsetLeft) / 20;
49             //调用了Math方法,floor是舍小数取整
50             speed = Math.floor(speed);
51             if (pto.offsetLeft == -200) {
52                 clearInterval(timer)
53             } else {
54                 pto.style.left = pto.offsetLeft + speed + 'px';
55             }
56         }
57 
58 
59 
60     }
61 </script>

 

posted @ 2016-11-02 14:20  rookieM  阅读(880)  评论(0编辑  收藏  举报