欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

让div运动起来 js实现缓动效果

程序员文章站 2023-02-25 12:59:06
本文实例为大家分享了js实现缓动效果的具体代码,供大家参考,具体内容如下 var tween = { linear:function(t,b,c,d){...

本文实例为大家分享了js实现缓动效果的具体代码,供大家参考,具体内容如下

var tween = {
  linear:function(t,b,c,d){
    return c*t/d + b;
  },
  easein:function(t,b,c,d){
    return c * ( t /= d ) * t + b;
  },
  strongeasein:function(t,b,c,d){
    return c * ( t /= d ) * t * t * t * t + b;
  },
  strongeaseout:function(t,b,c,d){
    return c * ( ( t = t / d -1 ) * t * t * t * t +1 ) + b;
  },
  sineasein:function(t,b,c,d){
    return c * ( t /= d ) * t * t + b;  
  },
  sineaseout:function(t,b,c,d){
    return c * ( ( t = t / d -1 ) * t * t *t +1 ) + b;
  }
};

var animate = function(dom){
  this.dom = dom;
  this.starttime = 0;
  this.startpos = 0;
  this.endpos = 0;
  this.propertyname = null;
  this.easing = null;
  this.duration = null;
}

animate.prototype.start = function(propertyname,endpos,duration,easing){
  this.starttime = +new date;
  this.startpos = this.dom.getboundingclientrect()[propertyname];
  this.propertyname = propertyname;
  this.endpos = endpos;
  this.duration = duration;
  this.easing = tween[easing];

  var self = this;
  var timeid = setinterval(function(){
    if(self.step() === false){
      clearinterval(timeid);
    }
  },19);
}

animate.prototype.step = function(){
  var t = +new date;
  if(t>=this.starttime + this.duration){
    this.update(this.endpos);
    return false;
  }
  var pos = this.easing(t-this.starttime, this.startpos, this.endpos - this.startpos, this.duration);
  this.update(pos);
}

animate.prototype.update = function(pos){
  this.dom.style[this.propertyname] = pos + 'px';
}

var div = document.getelementbyid('div');
var animate = new animate(div);
animate.start('left',500,1000,'strongeaseout');

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。