2008-11-02 47 views
1

我想建立一个动画运行一定次数的循环,并且在每次动画迭代之前运行一个函数。然而,时序结束了,它会执行n次回调,然后运行动画n次。例如:如何设置回调以在* jquery动画之前运行*?

for (var i=0;i<3;i++) { 
    console.log(i); 
    $('#blerg').animate({top:'+=50px'},75,'linear', function(){log('animated')}); 
} 

输出

0 
1 
2 
animated 
animated 
animated 

我就遇到了这个问题之前Scriptaculous的我切换到jQuery和发现了一个“beforeSetup”动画回调。有没有jQuery的等价物?

回答

2

动画是异步的。所以这些循环非常快速地运行,从三个动画开始,输出1,2和3.一段时间后,动画完成并输出动画x 3.这将解释您的输出。

有些递归怎么样?

do_animation(max_runs, total_runs) { 
    log(); 
    if (total_runs < max_runs) { 
     $(foo).animate(..., do_animation(max_runs, ++total_runs)); 
    } 
} 

do_animation(3,0);

试一下,让我知道它是如何运行的。

1

您也可以尝试使用队列功能。

http://docs.jquery.com/Effects/queue#callback

国内我还记得动画使用相同的执行队列,所以这在理论上应(未经测试)工作。

/* Safe Namespace + Onload : I do this everywhere */ 
jQuery(function($){ 
/* Calling this once instead of many times will save 
    a lot of wasted calls to document.getElementById + processing garbage 
    */ 
var blerg = $('#blerg'); 
var addStep = function(i) 
{ 
    blerg.queue(function(){ 
     console.log(i); 
     $(this).dequeue(); 
    }); 
    blerg.animate({top:'+=50px'},75,'linear'); 
    /* In theory, this works like the callback does */ 
    blerg.queue(function(){ 
     log('animated'); 
     $(this).dequeue(); 
    }); 
}; 

for (var i=0;i<3;i++) 
{ 
    /* I call a function here, because that way you don't need to worry 
    about the fact 'i' will reference the last value of 'i' when the code 
    gets around to executing. */ 
    addStep(i); 
} 
}); 

肯特,我不明白为什么你需要明确提出回调的 队列。不是你错了 - 如果回调是 animate()的一个参数,它就不起作用 - 但我只是好奇。

它不是必需的第二种情况,但我认为它更一致的,有点整洁代码所做的如果是要努力做更多的事情在回调阶段(例如,另一个动画)。

然后你只想把下一个动画调用中的第二blerg.queue后,

且不说它已经创造了位,程式精密的额外的好处整个执行序列定义它需要之前运行,使执行大部分是线性的。

因此,这使得代码仍然是“你怎么想它的工作原理”,并使它仍然运行“你需要它的工作方式”,而不必担心它的全部不同步性。 (这使得更少的越野车和更可维护的代码)

0

这两种解决方案的工作就像一个魅力!谢谢,MDCore和肯特!

肯特,我不太明白你为什么需要明确地把回调放在队列中。不是说你错了 - 如果回调是animate()的一个参数,它就不起作用 - 但我只是好奇而已。

相关问题