js-animate

封裝一個js的小型的animate

/*
* @Author: Administrator
* @Date:   2019-12-18 15:52:13
* @Last Modified by:   Administrator
* @Last Modified time: 2019-12-19 17:15:51
*/
function $(id){
    return document.getElementById(id);
}
function getStyle(obj, attr){
    if(window.getComputedStyle){
        return window.getComputedStyle(obj, null)[attr];
    }else{
        return obj.currentStyle[attr];
    }
}

function animate(obj, json, speed, callback){
    clearInterval(obj.timer); 
    obj.timer = setInterval(function () {
        var flag = true;                  
        for(var attr in json){
            var current = 0;
            var step = 0;
            if(attr == 'opacity'){ // 操作透明度屬性
                // 判斷如果是主流瀏覽器
                if('opacity' in obj.style){
                    current = getStyle(obj, attr) * 100;
                    step = (json[attr] * 100 - current) / 10;
                    step = step > 0 ? Math.ceil(step) : Math.floor(step);
                    var leader = (current + step) / 100
                    obj.style.opacity = leader;
                    if(leader != json[attr]){
                        flag = false;
                    }
                }else{ // IE6/7/8
                    current = getStyle(obj, 'filter');
                    current = parseInt(current.slice(current.indexOf('=') + 1));
                    step = (json[attr] * 100 - current ) / 10;
                    step = step > 0 ? Math.ceil(step) : Math.floor(step);
                    var leader = 'alpha(opacity=' + (current + step) + ')';
                    obj.style['filter'] = leader;
                    if(current + step != json[attr] * 100){
                        flag = false;
                    }
                }
            }else if(attr == 'zIndex'){ // 如果是設置z-index屬性,那麼就直接賦值,不需要考慮動畫變化的過程
                obj.style.zIndex = json[attr];
            }
            else{ // 設置 值帶有px爲單位的屬性
                current = parseInt(getStyle(obj, attr));
                step = (json[attr] - current) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                obj.style[attr] = current + step + "px";
                if(current != json[attr]){
                    flag = false;
                }
            }
        }
        if(flag){
            clearInterval(obj.timer);
            if(callback && typeof callback == 'function'){
                callback();                            
            }
        }
    }, speed);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章