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

时间:2008-09-16 18:00:41

标签: javascript jquery

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

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

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

4 个答案:

答案 0 :(得分:32)

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

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

答案 1 :(得分:16)

你想要的是一个队列。

查看参考页面http://api.jquery.com/queue/以获取一些工作示例。

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

//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") 
);

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