一、让div动起来

var oBtn = document.getElementById('btn1');
 var timer='';//设置定时器
oBtn.onclick=function startMove(){
  var oDiv = document.getElementById('div1');

  clearInterval(timer);//关闭原有的定时器,否则多个定时器会叠加
  timer=setInterval(function(){
    var iSpeed=3;
    if(oDiv.offsetLeft>=208){
      clearInterval(timer);
    }else{
    oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';
    }

  },30);
}

二、‘分享到’侧边栏

var timer=null;
function startMove(iTarget,iSpeed){
  var oDiv = document.getElementById('div1');
  clearInterval(timer);
  timer=setInterval(function(){
    if(oDiv.offsetLeft==iTarget){
      clearInterval(timer);
    }else{
      oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';
    }
  },30);
}

window.onload=function(){
  var oDiv = document.getElementById('div1');
  oDiv.onmouseover=function(){
    startMove(0,10);
  }
  oDiv.onmouseout=function(){
    startMove(-100,-10);
  }

}

三、图片淡入淡出效果

var timer=null;
var alpha=30;
function startMove(iTarget,iSpeed){
  var oImg = document.getElementById('img1');
  clearInterval(timer);
  timer=setInterval(function(){
    if(alpha==iTarget){
      clearInterval(timer);
    }else{
      alpha+=iSpeed;document.title=alpha;
      oImg.style.filter='alpha(opacity:'+alpha+')';
      oImg.style.opacity=alpha/100;
    }
  },30);
}

window.onload=function(){
var oImg = document.getElementById('img1');
oImg.onmouseover=function(){
  startMove(100,5);
}
oImg.onmouseout=function(){
  startMove(10,-5);
}

四、实现缓动效果

var oBtn = document.getElementById('btn1');
var timer='';
oBtn.onclick=function startMove(iTarget){
  var oDiv = document.getElementById('div1');

  clearInterval(timer);
  timer=setInterval(function(){
    var iSpeed=(300-oDiv.offsetLeft)/8;//缓动效果
    iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);//消除小数点值的bug
    document.title=iSpeed+'/'+oDiv.offsetLeft;
    if(oDiv.offsetLeft==300){
      clearInterval(timer);
    }else{
      oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';
    }

  },30);
}

五、缓动侧边栏

var timer=null;
function startMove(iTarget){
  var oDiv=document.getElementById('div1');
  clearInterval(timer);
  timer=setInterval(function(){
    var iSpeed=(iTarget-oDiv.offsetTop)/8;
    iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);

    if(oDiv.offsetTop==iTarget){
      clearInterval(timer);
    }else{
      oDiv.style.top=oDiv.offsetTop+iSpeed+'px';
    }
  },30);
}
window.onscroll=function(){
var oDiv = document.getElementById('div1');
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;

var t=scrollTop+(document.documentElement.clientHeight-oDiv.offsetHeight)/2;

startMove(parseInt(t));//消除抖动

}

六、匀速运动停止条件:与目标点无限接近即可

timer=setInterval(function(){
     var iSpeed=0;

    if(oDiv.offsetLeft<iTarget){

      iSpeed=7

    }else{

      iSpeed=-7

    }

    if(Math.abs(oDiv.offsetLeft-iTarget)<7){//是否到达终点
      clearInterval(timer);

      oDiv.style.top=iTarget+'px';

    }else{
       oDiv.style.top=oDiv.offsetLeft+iSpeed+'px';
    }
  },30);

05-11 03:09