JavaScript div 上下运动实例
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 <style> 8 #div1{width:100px;height:100px;background: red;position:absolute;left:30px;top:50px; border-radius: 50px;} 9 </style> 10 <script type="text/javascript"> 11 window.onload = function () { 12 var oBtn1 = document.getElementById('btn1'); 13 var oBtn2 = document.getElementById('btn2'); 14 var oDiv = document.getElementById('div1'); 15 16 oBtn1.onclick = function () { 17 doMove(oDiv, -12, 10); // 直接就回到原点,原因是没判断大于小于号 18 } 19 20 oBtn2.onclick = function () { 21 doMove(oDiv, 12, 800); 22 } 23 24 // obj--移动对象,dir--方向,target--目标点 25 function doMove(obj, dir, target) { 26 clearInterval(obj.timer); 27 obj.timer = setInterval(function () { 28 var speed = parseInt(getStyle(obj, 'left')) + dir; 29 if (speed > target && dir > 0) { // 往前跑 30 speed = target; 31 } 32 33 if (speed < target && dir < 0) { // 往后跑 34 speed = target; 35 } 36 obj.style.left = speed + 'px' 37 if (speed == target) { 38 clearInterval(obj.timer); 39 } 40 }, 30) 41 } 42 43 function getStyle(obj, attr) { 44 return getComputedStyle(obj)[attr]; 45 } 46 } 47 </script> 48 </head> 49 50 <body> 51 <input id="btn1" type="button" value="向前"> 52 <input id="btn2" type="button" value="向后"> 53 <div id="div1"></div> 54 </body> 55 56 </html>
obj--移动对象,dir--方向,target--目标点