js--同步运动json下

这一节针对上一节讲述的bug,我们来处理一下。

这个bug存在的原因就是,一旦只要有一个属性值达到目标值就会清除定时器,所以我们要改变 的就是清除定时器的那么部分。看下面的修改

var timer;
window.onload=function(){
    var div=document.getElementById("div1");
     div.onmouseover=function(){
         startMove(div,{210,height:400,opacity:100});
     }
     div.onmouseout=function(){
         startMove(div,{200,height:200,opacity:30})
     }
}

function startMove(obj,json,fn){
    clearInterval(timer);
    var index=0;
    timer=setInterval(function(){
        for(var attr in json){
        var icur;
        if(attr=="opacity"){
         icur=Math.round(parseFloat(getStyle(obj,attr))*100);
         
        }else{
            icur=parseInt(getStyle(obj,attr))
            
        }
        var speed=(json[attr]-icur)/8;
         speed=speed>0? Math.ceil(speed):Math.floor(speed);
          
        if(icur!=json[attr]){
            index=1;//当只要还有属性值不等于他的目标值时,index=0,这时就不清除掉定时器。
            if(fn){
                fn();
            }
        }else {
            index=0;
        }
            
        if(index==1){
            if(attr=="opacity"){
                obj.style.opacity=(icur+speed)/100;
                obj.style.filter="alpha(opacity"+(icur+speed)+")";
            }
                obj.style[attr]=parseInt(getStyle(obj,attr))+speed+"px";    
        }
        }
    },50)
    if(index=0){
        clearInterval(timer);
    }
}
 
 
 function getStyle(obj,attr){
     if(obj.currentStyle){
         return obj.currentStyle[attr];
     }else if(getComputedStyle){
         return getComputedStyle(obj,false)[attr];
     }
 }
原文地址:https://www.cnblogs.com/yuaima/p/5121549.html