JS运动基础(一)

 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>无标题文档</title>
 6 <style>
 7 #div1 {width:100px; height: 100px; background: red; position: absolute; left: 0px; top: 30px;}
 8 </style>
 9 <script>
10 /*
11 在js中,如果让一个页面元素动起来
12 */
13 window.onload = function() {
14     
15     var oBtn = document.getElementById('btn');
16     var oDiv = document.getElementById('div1');
17     var iTimer = null;
18     
19     //点击按钮,让div1横向向右移动
20     //定时器
21     
22     /*
23     1.清除定时器,保证运动过程中只有一个定时器在执行
24     2.开始定时器
25     3.开始运动(同时在运动加入判断,以便在需要的时候或者是满足某个要求停止运动)
26     */
27     oBtn.onclick = function() {
28         
29         clearInterval(iTimer);
30         
31         iTimer = setInterval(function() {
32             
33             //oDiv.style.left = oDiv.offsetLeft + 10 + 'px';
34             if (oDiv.offsetLeft == 500) {
35                 clearInterval(iTimer);
36             } else {
37                 oDiv.style.left = oDiv.offsetLeft + 10 + 'px';
38             }
39             
40         }, 30);
41         
42     }
43     
44 }
45 </script>
46 </head>
47 
48 <body>
49     <input type="button" value="动起来" id="btn" />
50     <div id="div1"></div>
51 </body>
52 </html>
原文地址:https://www.cnblogs.com/trtst/p/3757897.html