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);
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值