Fork me on GitHub

JavaScript Timer实现动画效果

 1 <style type="text/css">
 2     div {
 3         width: 100px;
 4         height: 50px;
 5         background: red;
 6         margin: 10px;
 7     }
 8 </style>
 9 <body>
10     <div></div>
11     <div></div>
12     <div></div>
13 </body>
14 <script type="text/javascript">
15     window.onload = function () {
16         var aDiv = document.getElementsByTagName('div');
17         for (var i = 0; i < aDiv.length; i++) {
18             aDiv[i].timer=null;
19             aDiv[i].onmouseover = function () {
20                 startMove(this, 400);
21             };
22             aDiv[i].onmouseout = function () {
23                 startMove(this, 100);
24             };
25         }
26     }
27     
28     function startMove(obj, iTarget) {
29         clearInterval(obj.timer);
30         obj.timer = setInterval(function () {
31             var speed = (iTarget - obj.offsetWidth) / 60;
32             speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
33             if (obj.offsetWidth == iTarget) {
34                 clearInterval(obj.timer);
35             } else {
36                 obj.style.width = obj.offsetWidth + speed + 'px';
37             }
38         }, 1);
39     }
40 </script>

 

posted @ 2015-05-12 13:49  Terry√  阅读(239)  评论(0编辑  收藏  举报