Chaining jQuery animations that affect different elements

前端 未结 4 491
闹比i
闹比i 2020-11-29 07:52
$(document).ready(function() {
    $(\"#div1\").fadeIn(\"slow\");
    $(\"#div2\").delay(500).fadeIn(\"slow\");
    $(\"#div3\").delay(2000).fadeIn(\"slow\");
    $(         


        
4条回答
  •  迷失自我
    2020-11-29 08:05

    I'd do it in a loop, as long as you're talking about a consistent increment (and as long as they appear in the same order on the page).

    $("#div1,#div2,#div3,#div4").each(function( idx ) {
        $(this).delay( idx * 1000 ).fadeIn("slow");
    });
    

    Example: http://jsfiddle.net/km66t/

    This uses the index passed by .each() to increment the delay.

    So you're effectively doing:

    $("#div1").delay( 0 ).fadeIn("slow");
    $("#div2").delay( 1000 ).fadeIn("slow");
    $("#div3").delay( 2000 ).fadeIn("slow");
    $("#div4").delay( 3000 ).fadeIn("slow");
    

    EDIT: To hopefully address the issue in the comment below, you could instead store an Array of the delays you want to use, and access the proper index of the Array using the index from .each().

    var delays = [0, 1000, 2000, 4000];
    
    $("#div1,#div2,#div3,#div4").each(function( idx ) {
        $(this).delay( delays[ idx ] ).fadeIn("slow");
    });
    

提交回复
热议问题