1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>多物体运动</title> 6 <style> 7 div{ 8 100px; 9 height: 50px; 10 background: red; 11 margin: 10px; 12 } 13 </style> 14 </head> 15 <body> 16 <div></div> 17 <div></div> 18 <div></div> 19 <script> 20 var aDiv = document.getElementsByTagName('div'); 21 for(var i = 0;i < aDiv.length;i ++){ 22 aDiv[i].timer = null; 23 aDiv[i].onmouseover = function(){ 24 startMove(this,400); 25 } 26 aDiv[i].onmouseout = function(){ 27 startMove(this,100); 28 } 29 } 30 31 function startMove(obj,iTarget){ 32 clearInterval(obj.timer); 33 34 obj.timer = setInterval(function(){ 35 var speed = (iTarget - obj.offsetWidth)/6; 36 37 speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); 38 39 if(obj.offsetWidth == iTarget){ 40 clearInterval(obj.timer); 41 }else{ 42 obj.style.width = obj.offsetWidth + speed + 'px'; 43 } 44 },30) 45 } 46 </script> 47 </body> 48 </html>
效果: