JavaScript多物體運動二

JavaScript多物體運動二javascript

html:css

<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>

css:html

<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:java

<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)
   }

效果:this

相關文章
相關標籤/搜索