第三十一节 JavaScript定时器制作往复运动动画
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>定时器动画</title> 6 <script type="text/javascript"> 7 window.onload = function(){ 8 var oDiv = document.getElementById('div1'); 9 var i = 0 10 var iSpeed = 3; 11 // 通过增加一个中间变量iSpeed来实现 12 var timer01 = setInterval(function(){ 13 i+=iSpeed; 14 oDiv.style.left = i+ 'px'; 15 16 if (i>960) { 17 iSpeed = -3; 18 } 19 if (i<0) { 20 iSpeed = 3; 21 } 22 },10) 23 } 24 25 </script> 26 <style type="text/css"> 27 .box{ 28 width: 200px; 29 height: 300px; 30 background-color: gold; 31 position: absolute; 32 left: 0px; 33 } 34 </style> 35 </head> 36 <body> 37 <div class="box" id="div1"></div> 38 </body> 39 </html>