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