<div id="div" style="position: absolute; background-color: skyblue;">I am a div</div>
Copy the code
/* @param {number} t * @param {number} b beginning value * @param {number} c change in Value (variable) * @param {number} d (total animation time) */ 
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 + 1) + b; }};var Animate = function (dom) {
    this.dom = dom                  // The dom node to animate
    this.startTime = 0              // Animation start time
    this.startPos = 0               // The initial position of the DOM
    this.endPos = 0                 // Dom target location
    this.propertyName = null        // The name of the CSS property of the DOM node to be modified
    this.easing = null              // Slow algorithm
    this.duration = null            // Animation duration
}

Animate.prototype.start = function (propertyName, endPos, duration, easing) {
    this.startTime = +new Date;     // Start time of animation
    this.startPos = this.dom.getBoundingClientRect()[ propertyName ]    // Dom node initial position
    this.propertyName = propertyName    // The name of the CSS property of the DOM node to be changed
    this.endPos = endPos    // dom node target location
    this.duration = duration    // Animation duration
    this.easing = tween[ easing ]   // Slow algorithm

    var self = this
    var timeId = setInterval( function() {
        if (self.step() === false) {
            clearInterval( timeId )
        }
    }, 1000 / 60);
}

Animate.prototype.step = function () {
    var t = +new Date;      // Get the current time
    if (t >= this.startTime + this.duration) {
        this.update( this.endPos )  // When the time is exceeded, correct the final destination position
        return false
    }
    var pos = this.easing( t - this.startTime, this.startPos, 
        this.endPos - this.startPos, this.duration)
    // pos is the current position of the ball
    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.'sineaseOut' );
// animate.start( 'top', 500, 1000, 'easeIn' );
Copy the code