javascript实现(分享到xxx)的小实例

javascript实现(分享到的小实例)

这个算值运动的一个实例应用吧

HTML代码:

   <div id="tag">
   <span id="showInfo">分享到</span>
   </div>

css代码:

#tag{
    height:200px;
    width:200px;
    background:green;
    position:absolute;
    top:100px;
    left:-200px;

}
#tag span{
    height:60px;
    width:20px;
    background:red;
    position:absolute;
    top:90px;
    left:200px;
    z-index:10px;
    cursor:pointer;
    
}

初略的js代码

 var speed=6;
 var Timer=null;
 function show(obj){
     clearInterval(Timer);   
      Timer=setInterval(function (){
          if(obj.offsetLeft<=0){ 
           obj.style.left=obj.offsetLeft+speed+"px";
          }else{
             clearInterval(Timer);  
          }
     },30)
     
 };
  function hide(obj){
     clearInterval(Timer);   
      Timer=setInterval(function (){
          if(obj.offsetLeft<=-200){ 
             clearInterval(Timer);  
          }else{
            
            obj.style.left=obj.offsetLeft-speed+"px";
          }
     },30)
     
 }

 window.onload=function (){
     var obj=document.getElementById("tag");
      obj.onmouseover=function(){
          show(obj);
      };
      obj.onmouseout=function (){
           hide(obj);
        
      };
 }

 

优化代码一

我们可以分析看出hide 和 show 之间的区别;就是停止点判读 和速度的方向选择

最简单的优化方法就是,将两个函数之间不同的地方提取出来

用参数表示滴呀

  function getPublic(obj,s,speed){
      clearInterval(Timer);
      Timer=setInterval(function (){
          if(obj.offsetLeft==s){   //这里有待优化,因为在取等的时候,可能会掉过该“阀门”,而取大于或者小于的时候,可能会超出或者减少
              clearInterval(Timer);  
          }else{
             obj.style.left=obj.offsetLeft+speed+"px";
          }
      },30) 
  }
 //这个是代码实现底部滴呀
 //然后我们进行后话滴呀
 //
 window.onload=function (){
     var obj=document.getElementById("tag");
      obj.onmouseover=function(){
            getPublic(obj,0,10);
      };
      obj.onmouseout=function (){
            getPublic(obj,-200,-10);
        
      };
 }

最终优化代码

速度的正负,我们可以通过起点和目标之间的距离相减来进行判断滴呀 

代码:

function getPublic2(obj,s){
      clearInterval(Timer);
      var speed=0;
      if((s-obj.offsetLeft)>0){
          speed=5;
      }else{
          speed=-5;
      }
      Timer=setInterval(function (){
          if(obj.offsetLeft==s){   //这里又待优化,应为在去等的时候,可能会掉过该“阀门”
              clearInterval(Timer);  
          }else{
             obj.style.left=obj.offsetLeft+speed+"px";
          }
      },30) 
  }
 //这个是代码实现底部滴呀
 //然后我们进行后话滴呀
 //
 window.onload=function (){
     var obj=document.getElementById("tag");
      obj.onmouseover=function(){
            getPublic2(obj,0);
      };
      obj.onmouseout=function (){
            getPublic2(obj,-200);
        
      };
 }

当让我们obj也是可以提取的,这个太简单,我都不写了;

 效果:

posted @ 2016-01-29 20:49  咕-咚  阅读(852)  评论(0编辑  收藏  举报