如何使jQuery效果按顺序运行,而不是同时运行?

如何在jQuery中按顺序运行两个效果,而不是同时运行? 以这段代码为例:

$("#show-projects").click(function() { $(".page:visible").fadeOut("normal"); $("#projects").fadeIn("normal"); }); 

fadeOut和fadeIn同时运行,我如何让它们一个接一个地运行?

您可以为效果完成后运行的效果函数提供回调。

 $("#show-projects").click(function() { $(".page:visible").fadeOut("normal", function() { $("#projects").fadeIn("normal"); }); }); 

你想要的是一个队列。

有关一些工作示例,请查看参考页面http://api.jquery.com/queue/ 。

是否必须有目标? 肯定你可以使用随机目标按顺序对事件进行排队,只要目标是常量…下面我正在使用动画目标的父节点来存储队列。

 //example of adding sequential effects through //event handlers and a jquery event trigger jQuery( document ).unbind( "bk_prompt_collapse.slide_up" ); jQuery( document ).bind( "bk_prompt_collapse.slide_up" , function( e, j_obj ) { jQuery(j_obj).queue(function() { //running our timed effect jQuery(this).find('div').slideUp(400); //adding a fill delay to the parent jQuery(this).delay(400).dequeue(); }); }); //the last action removes the content from the dom //if its in the queue then it will fire sequentially jQuery( document ).unbind( "bk_prompt_collapse.last_action" ); jQuery( document ).bind( "bk_prompt_collapse.last_action" , function( e, j_obj ) { jQuery(j_obj).queue(function() { //Hot dog!! jQuery(this).remove().dequeue(); }); }); jQuery("tr.bk_removing_cart_row").trigger( "bk_prompt_collapse" , jQuery("tr.bk_removing_cart_row") ); 

不确定它是否可能,但似乎你可以绑定.dequeue()来触发另一个jquery事件触发,而不是在上面的例子中触发内联? 有效地停止动画队列?

 $( "#foo" ).fadeOut( 300 ).delay( 800 ).fadeIn( 400 );