javascript动画效果——链式运动,同时运动

1.实现链式运动的一个关键是利用回调函数
2.下面是一个比较实用的框架,但不是完美的,特别是在同时运动上,还需要用到json

function startMove(obj,attr,iTarget,fn){    //添加一个回调函数fn
clearInterval(obj.timer);//1.2+++
obj.timer=setInterval(function(){//1.2+++
    var icur=null;
//1.判断类型
if(attr=='opacity'){
    icur=Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
    icur=parseInt(getStyle(obj,attr));
}
//2.算速度
var speed=(iTarget-icur)/8;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
//3.检测停止
if(icur==iTarget){
    clearInterval(obj.timer);
if(fn){ //判断是否存在回调函数,并调用
    fn();
}
}else{
    if(attr=='opacity'){
        obj.style.filter='alpha(opacity:'+(icur+speed)+')';
        obj.style.opacity=(icur+speed)/100;
    }else{
        obj.style[attr]=icur+speed+'px';
    }

}
},30);
}
function getStyle(obj,attr){
    if(obj.currentStyle){
        return obj.currentStyle[attr];
    }else{
        return getComputedStyle(obj,false)[attr];
    }
}`
3.完美型的运动框架
`function startMove(obj,json,fn){

clearInterval(obj.timer);//清除定时器,避免重复生成多个定时器
obj.timer=setInterval(function(){
var flag=true;//假设刚开始时所有运动都已完成
for (var attr in json) {//遍历json

    var icur=null;
//1.判断类型
if(attr=='opacity'){
    icur=Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
    icur=parseInt(getStyle(obj,attr));
}
//2.算速度
var speed=(json[attr]-icur)/10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
//3.检测停止
if(icur!=json[attr]){
    flag=false;
}
if(attr=='opacity'){
    obj.style.filter='alpha(opacity:'+(icur+speed)+')';
    obj.style.opacity=(icur+speed)/100;
}else{
    obj.style[attr]=icur+speed+'px';
}   
}
if (flag) {//当所有运动都完成时,清除定时器
    clearInterval(obj.timer);
    if(fn){
        fn();
    }
}
},30);
}


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

你可能感兴趣的:(javascript动画效果——链式运动,同时运动)