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

javascript动画效果之匀速运动

2016-11-02 09:29 483 查看

html和css写在一起方便看,div通过定位设置为-200隐藏,span也是通过定位定在div靠左的中间

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 <body>
37     <div id="div">
38         <span id="show">show</span>
39     </div>
40
41 42 </body>
43
44 </html>

js部分是通过添加定时器设置offsetLeft值的自增和自减,来达到div显示和隐藏的效果

1 <script>
2         function $(id) {
3             return typeof id === "string" ? document.getElementById(id) : id;
4         }
5
6         window.onload = function() {
7             //定义了隐藏的div为pto
8             var pto = $("div");
9             //定义了按钮span为 btn
10             var btn = $("show");
11             //定义一个空的定时器
12             var timer = null;
13
14             //按钮绑定一个鼠标移进事件
15             btn.onmouseenter = start;
16
17             //自定义函数用于自动增加
18             function start() {
19                 //防止自加速,每次开始前都要清除定时器
20                 clearInterval(timer);
21                 //定义一个定时器
22                 timer = setInterval(show, 30);
23             }
24
25             //自定义函数,直到offsetLeft的值为0,否则offsetLeft的值从-200一直自增5
26             function show() {
27                 if (pto.offsetLeft == 0) {
28                     clearInterval(timer);
29                 } else {
30                     pto.style.left = pto.offsetLeft + 5 + 'px';
31                 }
32             }
33
34             //绑定一个鼠标移出事件
35             btn.onmouseleave = back;
36
37             //自定义函数,用于自动减少
38             function back() {
39                 clearInterval(timer);
40                 timer = setInterval(clear, 30);
41             }
42
43             //自定义函数,直到offsetLeft的值为-200,否则offsetLeft的值一直自减5
44             function clear() {
45                 if (pto.offsetLeft == -200) {
46                     clearInterval(timer);
47                 } else {
48                     pto.style.left = pto.offsetLeft - 5 + 'px';
49                 }
50             }
51
52         }
53     </script>

 

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