//获取非行间样式
function getStyle(obj,attr){
    if(obj.currentStyle){
        return obj.currentStyle[attr];
    }else{
        return getComputedStyle(obj,false)[attr];
    }
}
 
//运动
function action(obj,json,fn){
    //关闭此obj的定时器,防止多次触发冲突
    clearInterval(obj.timer);
    obj.timer = setInterval(function(){
 
        //当flag为true时,关闭所有定时器
        var flag = true;
 
        //循环遍历json里的所有 key 即 obj的属性
        for(var attr in json){
            //先声明当前属性的值为0
            var i_cur = 0;
            //获取此非行间样式即属性的值(opacity 比较特殊,因为其没有px,先*100为了去掉小数点,防止bug)
            if(attr == "opacity"){
                i_cur = parseInt(getStyle(obj,attr)*100)
            }else{
                i_cur = parseInt(getStyle(obj,attr));
            }
           //速度
            //定义速度,其公式为 (目标值 - 获取的当前属性的值)/8 8是比较适合的
            var speed = (json[attr] - i_cur)/8;
            //取整,杜绝bug
            speed = speed>0?Math.ceil(speed):Math.floor(speed);
 
            //判断终止条件
            //对于所有的属性,只要值未达到目标值,定时器就不会关闭
            if(json[attr] != i_cur){
                flag = false
            };
            //运动
 
            //若属性为 透明,则做特殊计算
            if(attr == "opacity"){
                obj.style.opacity = (i_cur + speed)/100;
                obj.style.filter = "alpha(opacity = "+(i_cur+speed)+")"
            }else{
                //否则则 直接运动+px
                obj.style[attr] = (i_cur + speed) +"px"
            }
        }
        //关闭 并 回调
        //所有属性达到目标值,关闭当前的定时器
        if(flag){
            clearInterval(obj.timer)
            //回调函数,用于一个定时器可以触发多个物体运动
            if(fn){
                fn()
            }
            // 简写为 fn&&fn();
        }
 
    },30)
}
 
//如何调用的小例子
oBox1.onmouseover = function(){
    action(this,{width:400,height:200},function(){
        action(oBox2,{opacity:100})
   });
}
 
oBox2.onmouseover = function(){
    action(this,{opacity:100},function(){
        action(oBox1,{width:300,height:180})
    });
}
posted on 2018-08-28 10:28  玩儿味_cai  阅读(149)  评论(0编辑  收藏  举报