JavaScript多物体运动二
html:
<body> <div></div> <div></div> <div></div> <div></div> </body>
css:
<style type="text/css"> div{ height:150px; width:200px; background:green; margin-left:10px; float:left; opacity:0.3; filter:alpha(opacity:30); } </style>
javascript:
<script type="text/javascript"> //物体多了,就要考虑到我们的面向对象的方式来实现滴呀 window.onload=function (){ var objs=document.getElementsByTagName('div'); var len=objs.length; for(var i=0;i<len;i++){ objs[i].Timer=null; //添加一个定时器的属性 objs[i].alpha=30; //添加一个控制透明度的属性滴呀(初始化为30) objs[i].onmouseover=function(){ changeOpacity(this,100); //移入的时候,就全部变成完整的颜色 } objs[i].onmouseout=function (){ //移出的时候,就变回原来的颜色滴呀 changeOpacity(this,30); } } } function changeOpacity(obj,iTarget){ //一步步的接近面向对象编码方式了滴呀 clearInterval(obj.Timer); obj.Timer=setInterval(function (){ var speed=(iTarget-obj.alpha)/8; speed=speed>0?Math.ceil(speed):Math.floor(speed); if(obj.alpha==iTarget){ clearInterval(obj.Timer); }else{ obj.alpha+=speed; //考虑到兼容性 obj.style.opacity=(obj.alpha)/100; obj.style.filter='alpha(opacity:'+obj.alpha+')'; } },30) }
效果: