zoukankan      html  css  js  c++  java
  • JavaScript多物体运动一

    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)
       }
  • 相关阅读:
    linux磁盘简介
    linux用户管理、su和sudo、文件权限、SUID/SGID/SBIT
    dubbo框架的使用方法。。。
    Linux 配置 dubbo 和 dubbo的简单介绍。
    单列模式简单介绍
    Linux配置zookeeper 和zookeeper简单介绍
    Linux配置 ftp 和 ftp简单介绍
    正向代理 、反向代理, 和 Linux系统配置nginx。
    Linux配置Redis集群 和 缓存介绍。
    Linux 集群 和免秘钥登录的方法。
  • 原文地址:https://www.cnblogs.com/mc67/p/5195751.html
Copyright © 2011-2022 走看看