wait for each jQuery

前端 未结 3 952
南旧
南旧 2021-01-12 06:15

I\'m trying to make a div fade in/out that\'s within an each statement. The problem is that next item is called before the fade in/out is complete.



        
3条回答
  •  一生所求
    2021-01-12 06:52

    How about this, animate by going through each items in the array within the function?

    var elements = [ "one", "two", "three"];
    animate(elements);
    
    function animate( elements, index )
    {
        if(!index) index = 0;
        var box = '#' + elements[index];
        var $$box = $("#box");
        console.log( 'start - ' + elements[index] );
        $$box.fadeOut( 500, function( )
        {
            console.log('showing - ' + elements[index]);
            $$box.fadeIn( 500, function() {
                console.log( 'end - ' + elements[index] );
                if(elements[++index]) animate(elements, index);
            } ).css('backgroundColor','white');
        });
    }
    

    You can even loop back to the start if you want:

    var elements = [ "one", "two", "three"];
    animate(elements);
    
    function animate( elements, index )
    {
        if(!index) index = 0;
        var box = '#' + elements[index];
        var $$box = $(box);
        console.log( 'start - ' + elements[index] );
        $$box.fadeOut( 500, function( )
        {
            console.log('showing - ' + elements[index]);
            $$box.fadeIn( 500, function() {
                $$box.css('backgroundColor','white');
                console.log( 'end - ' + elements[index] );
                // go to next element, or first element if at end
                index = ++index % (elements.length);
                animate(elements, index);
            } );
        }).css('backgroundColor', 'aqua');
    }
    

提交回复
热议问题