JavaScript多物体运动一

本文介绍使用JavaScript实现多个HTML元素动态调整宽度的方法。通过监听鼠标悬停事件,结合定时器和面向对象思想,使每个元素能独立地平滑过渡到目标宽度。文章最后修复了一个与offsetWidth属性相关的bug,并提供了完整的修复代码。

JavaScript多物体运动一

html:

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

css:

 div{
     height:30px;
     width:50px;
     background:green;
     margin:10px;
 }

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].onmouseover=function(){
              moreMove(this,400);
          }
          objs[i].onmouseout=function (){
              moreMove(this,50);
          }
       }
   }
   function moreMove(obj,iTarget){
       //一步步的接近面向对象编码方式了滴呀
      clearInterval(obj.Timer);
      obj.Timer=setInterval(function (){
           var speed=(iTarget-obj.offsetWidth)/8;
           speed=speed>0?Math.ceil(speed):Math.floor(speed);
           if(obj.offsetLeft==iTarget){
             clearInterval(obj.Timer);
           }else{
             obj.style.width=obj.offsetWidth+speed+'px';
             
           }
      },30)
   }

效果:

 

这段效果,还是有一个bug的,是关于offsetWidth的,具体的请看, JavaScript中width和offsetWidth的区别(动画中)

经过修复后的源代码:

 function getStyle(obj,name){
         if(obj.currentStyle!=undefined){
            return obj.currentStyle[name];
         }else{
             return getComputedStyle(obj,false)[name];
         }
     }
   function moreMove(obj,iTarget){
       //一步步的接近面向对象编码方式了滴呀
      clearInterval(obj.Timer);
      obj.Timer=setInterval(function (){
          var width=parseInt(getStyle(obj,'width'));
           var speed=(iTarget-width)/8;
           speed=speed>0?Math.ceil(speed):Math.floor(speed);
           if(obj.offsetLeft==iTarget){
             clearInterval(obj.Timer);
           }else{
             obj.style.width=width+speed+'px';
             
           }
      },30)
   }

 

转载于:https://www.cnblogs.com/mc67/p/5195751.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值