简体   繁体   中英

Fade in elements one after another

Here is my code, it works but I would like to use the loop to clean up the code. Instead of having so many lines of code. I tried replacing the [0] with [i] but it would just make everything fadein together.

JSFIDDLE

var $icons = $('#header li').hide();

for(var i = 0; i < $icons.length; i++) {
    $($icons[0]).fadeIn(function() {
        $($icons[1]).fadeIn(function() {
            $($icons[2]).fadeIn(function() {
                $($icons[3]).fadeIn(function() {
                    $($icons[4]).fadeIn(function() {
                        $($icons[5]).fadeIn(function() {
                            $($icons[6]).fadeIn(function() {
                                $($icons[7]).fadeIn(function() {
                                    $($icons[8]).fadeIn(function() {
                                        $($icons[9]).fadeIn(function() {

                                        });
                                    });
                                });
                            }); 
                        });
                    });
                });
            }); 
        });
    });
}

You could use recursion:

function FadeMe($array, index) {
    if (index >= $array.length) return;

    $array.eq(index).fadeIn(function() {
        if (index + 1 < $array.length) {
            FadeMe($array, index + 1);
        }
    });
}

var $icons = $('#header li').hide();
FadeMe($icons, 0);

Fiddle: http://jsfiddle.net/0v3L0g6t/

Try this:

$icons.each(function(index) {
    $(this).delay(400*index).fadeIn(300);
});

DEMO

Try this:

var $icons = $('#header li').hide();

function doSetTimeout(i) {
      setTimeout(function() { $icons[i].fadeIn('slow'); }, 1000);
    }

for (var i = 0; i < $icons.length; i++){
      doSetTimeout(i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM