javascript封装animate动画

面向对象式:

Element.prototype.animate=animate;
Element.prototype.getStyle=getStyle;
function animate(json,callback) {
    clearInterval(this.timer);
    for (var attr in json) {
        var that = this;
        this.timer = setInterval(function () {
            if (attr == 'opacity') {
                that.icur = Math.round(parseFloat(that.getStyle()[attr]) * 100);
            } else {
                that.icur = parseInt(that.getStyle()[attr]);
            }
            that.speed = (parseInt(json[attr]) - that.icur) / 10;
            that.speed = that.speed > 0 ? Math.ceil(that.speed) : Math.floor(that.speed);
            if (attr == 'opacity') {
                that.style.filter = 'alpha(opacity:' + that.icur + that.speed + ')';
                that.style.opacity = (that.icur + that.speed) / 100;
            } else {
                that.style[attr] = that.icur + that.speed + "px";
            };
            if(that.icur==parseInt(json[attr])){
                //flags=true;
                clearInterval(that.timer);
                if(callback){
                    callback();
                }
            }
        }, 20);
    }
}
function getStyle() {
    if (this.currentStyle) {
        return this.currentStyle;
    } else {
        return document.defaultView.getComputedStyle(this, null);
    }
}

函数式:

// Element.prototype.animate=animate;
Element.prototype.getStyle = getStyle;
function animate(obj, json, callback) {
    //var flags=false;
    clearInterval(obj.timer);

    for (var attr in json) {
        //var that = this;
        var icur = 0, speed = 0;
        obj.timer = setInterval(function () {
            if (attr == 'opacity') {
                icur = Math.round(parseFloat(obj.getStyle()[attr]) * 100);
            } else {
                icur = parseInt(obj.getStyle()[attr]);
            }
            speed = (parseInt(json[attr]) - icur) / 10;
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
            if (attr == 'opacity') {
                obj.style.filter = 'alpha(opacity:' + icur + speed + ')';
                obj.style.opacity = (icur + speed) / 100;
            } else {
                obj.style[attr] = icur + speed + "px";
            };
            if (icur == parseInt(json[attr])) {
                //flags=true;
                clearInterval(obj.timer);
                if (callback) {
                    callback();
                }
            }
        }, 20);
    }
}
function getStyle() {
    if (this.currentStyle) {
        return this.currentStyle;
    } else {
        return document.defaultView.getComputedStyle(this, null);
    }
}

 

原文地址:https://www.cnblogs.com/wangshengli520/p/10416997.html