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);
}
发布了84 篇原创文章 · 获赞 204 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44983621/article/details/103619282
今日推荐