js--同步运动json上

如何实现几个属性的同时变化?这个问题需要运用到json,这里我们先来简要的介绍一下json

json的形式是这样的,他的元素是有一对对的键值对组成的{name1:value1,name2:value2,name3:value3.....}

遍历它的方式

for(var name in json){

alert(name);

}

依次获得是name1,name2,name3,.....

如果是alert(json[name])那么获得将是它的值,即value1,value2,value3.....我们接下来结合json来实现一下同时运用

var timer;
window.onload=function(){
    var div=document.getElementById("div1");
     div.onmouseover=function(){
         startMove(div,{400,height:400,opacity:100});
     }
     div.onmouseout=function(){
         startMove(div,{200,height:200,opacity:30});//这里我们传入的是一个json对象,json中的元素是属性,值对应的而是属性值。
     }
}

function startMove(obj,json,fn){
    clearInterval(timer);
    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;//这里我们通过json[attr]来获取属性值
         speed=speed>0? Math.ceil(speed):Math.floor(speed);
          
        if(icur==json[attr]){
            clearInterval(timer);
            if(fn){
                fn();
            }
        }else{
            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)
}
 
 
 function getStyle(obj,attr){
     if(obj.currentStyle){
         return obj.currentStyle[attr];
     }else if(getComputedStyle){
         return getComputedStyle(obj,false)[attr];
     }
 }

这个程序中其实存在一个bug,这个bug是如果我们把宽的属性设置为210的话,那么几个属性同时运动,那么宽肯定是先达到目标,其他几个还未达到相应为值,那么此时由于宽到达了目标,就执行了clearInterval就删除了定时器,这时,其他的几个属性也停止运动了。这样就是明显的一个bug

如何解决这个问题呢?

下一节,我将告诉如何解决这个bug

原文地址:https://www.cnblogs.com/yuaima/p/5121430.html