JS属性动画框架

2016-10-19  本文已影响64人  SSBun

使用js实现的属性动画框架:

function animation(obj,json,callback) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function() {
        var flag = true;
        for (var style in json)  {
            var target = json[style];
            var objStyle;
            if (style === 'opacity') {
                objStyle = Math.round(getStyle(obj,style) * 100);
            }
            else {
                objStyle = parseInt(getStyle(obj,style));
            }
            if (objStyle != target) {
                flag = false;
            }
            var speed = (target - objStyle)/10;
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
            if (style === 'opacity') {
                obj.style[style] = objStyle + speed;
            }
            else {
                obj.style[style] = objStyle + speed + 'px';
            }
            if (flag) {
                if (callback) {
                    callback();
                }
            }
        }
    },30)
}

function getStyle(obj,style) {
    if (obj.currentStyle) {
        return obj.currentStyle(style);
    }
    else {
        return getComputedStyle(obj,false)[style];
    }
}
上一篇下一篇

猜你喜欢

热点阅读