JS-运动框架

写这段代码,是因为之前看过某前RD写过,但在测试过程中发现有不完美的地方。

问题在于判断运动停止条件这里,对于之前停止的判断太片面,只能判断一个条件值时的情况,对于多条件时,会发现运动后的各项值并未达到目标值。

在这里我对每个值都做个TRUE,FALSE判断,确保各项都达到TRUE才停止运动。

测试地址:http://demo.xinanzhongxue.com/html/startMove.html

/*------------------------------------
 * FileName: startMove.js
 *------------------------------------
 * Param: 
 *           obj: The object of element.
 *           json: The data of json.
 *                For example: {width:100,height:200,opacity:80}
 *      second: the millisecond of time.
 *          fn: the function of callback.
 */
 
 
function startMove(obj,json,second,fn){
    clearInterval(obj.timer);
    var stop = true;
        obj.timer=setInterval(function(){                                       
        var stopx = {};
        for (var attr in json){    
            stopx[attr] = true;
            if(attr=='opacity'){
                var iCur=parseInt(Math.floor(parseFloat(getStyle(obj,attr))*100));
            }else{
                var iCur=parseInt(getStyle(obj,attr));
            }
            
            var speed=(json[attr]-iCur)/10;
            speed = speed >0 ? Math.ceil(speed) : Math.floor(speed);
            if(json[attr]!=iCur){
                    stopx[attr] = false;
                    stop=false;
                    if(attr=='opacity'){                       
                        obj.style.filter='alhpa(opacity:'+(iCur+speed)+')';
                        obj.style.opacity=(iCur+speed)/100;                    
                    }else{
                        obj.style[attr]=iCur+speed+'px';
                    }            
            }else{
                    stopx[attr] = true;
                    stop=true;
            }            
        }
        
        for(var j in stopx){
            if(stopx[j] == false)
                stop = false;
        }
        if(stop){
            for (var attr in json){
                if(attr=='opacity'){
                    var iCur=parseInt(Math.floor(parseFloat(getStyle(obj,attr))*100));
                }else{
                    var iCur=parseInt(getStyle(obj,attr));
                }
            }
            clearInterval(obj.timer);
            if(fn){     fn();    }
        }

    },second);
}

function getStyle(obj,attr){
    if(document.currentStyle){
        return obj.currentStyle[attr];
    }else{
        return window.getComputedStyle(obj,false)[attr];
    }

}

 

posted on 2014-04-22 18:45  徐明轩  阅读(344)  评论(2编辑  收藏  举报

导航