Jquery .each() including a delay looking for clean

2020-02-28 06:52发布

问题:

To be short, I am looking for a jQuery loop that will select each div with a class (approx 10 small divs in a line) then execute some code on each div specifically fade out and in the image contained in the div and then pause and move on and do the same to the next div.

This loop fades out/in all of the contained images at the same time...

$('.div_class').each(function() {
    $(this).children().fadeOut('fast', function() {
        $(this).fadeIn('slow');
    });
});

I have looked at the jquery functions delay() and setInterval() and the native JavaScript function setTimeout().

It seems I either cant get them to work at all or the examples I have seen are lengthy and complicated. With the magic of jquery it seems I should be able to add very little code the the loop above for it to work in series.

As mentioned, I'm looking for a clean simple example.

回答1:

You can use .delay() in combination with the index the .each() provides to the callback, like this:

$('.div_class').each(function(i) {
    $(this).children().delay(800*i).fadeOut('fast', function() {
        $(this).fadeIn('slow');
    });
});

This would do them back to back (fast = 200 + slow = 600), if you wanted more delay just increase that 800 to whatever you want. In the above example the first runs immediately, the next 800ms later, the next 800 after that, etc.



回答2:

$('.div_class').each(function(index) {
    // delay inserted before effect (based off index)
    $(this).children().delay(index * 1000).fadeOut('fast', function() {
        $(this).fadeIn('slow');
    });
});

* Glares at Nick *

Here is another way it could be done. This doesn't use a timed delay as above, but rather uses a recursive approach where the complete of one animation will result in the execution of the next.

function animate (elms) {
   var target = elms[0]
   if (target) { // guard to ensure still more
       $(target).children().fadeOut('fast', function() {
           $(this).fadeIn('slow')
           // o/` take one down, pass it around,
           //     98 elements of goop in the list o/`
           animate(elms.slice(1))
       }
   }
}
animate($('.div_class').get())