標籤:c style class blog code java
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>