0

我的大脑要爆炸了..为什么这不起作用?我试图用时间间隔为一些 div 设置动画并尝试编写更少的代码,但这不起作用

    var cargaCont = function(){
        o = 1;
        var animacion = function(i){
            $('#page2txt'+i).animate({
                height:'20'
            },200,function(){
                $('#page2img'+i).animate({
                    left:'0',
                    right:'0'
                },200,function(){
                    i++;
                    return i;
                });
            });
        }
        while(o < 3){
            setTimeout(function(){o = animacion(o);},200);
        }   
    }
4

2 回答 2

1

这段代码的问题:

while(o < 3){
    setTimeout(function(){o = animacion(o);},200);
} 

setTimeout在执行延迟的函数时,o已经是 3,因此所有调用都animacion传递 3 而不是 1 和 2。

o为了规避这个问题,您应该使用立即函数“本地化” 的值。

while(o < 3){
    //o out here is from cargaCont
    (function(o){
        //override o by naming the passed variable o
        setTimeout(function(){
            o = animacion(o); //now o refers to the local o
        },200);
    }(o)); //execute inner function, passing in o
} 

这使得o函数使用的 insetTimeout绑定到o本地函数的 而不是函数ocargaCont

于 2012-07-19T07:31:58.123 回答
0

我不是 100% 确定你到底要做什么,但我猜你基本上想循环播放一些动画,可能是这样的:

var cargaCont = function(){
    var i = 1,
        animacion = function(i){
            $('#page2txt'+i).animate({
               height:'20'
           },200,function(){
               $('#page2img'+i).animate({
                   left:'0',
                   right:'0'
               },200,function(){
                   if(i < 3){
                      animacion(++i);
                   }
               });
           });
       };
    animacion(i);
};

根据您的感觉进行编辑或发布一些标记以进一步解释。

干杯。

于 2012-07-19T08:20:06.247 回答