jQuery animation queues across multiple elements

2019-01-24 17:10发布

This question is similar to this one about animation queues, but the answers in that thread are very specific and not easily generalised.

In my web application, messages are reported back to the user (info boxes, errors & warnings, etc) by outputting a div with class="alert" eg:

<div class="alert">Login successful</div>
<div class="alert">You have new messages waiting</div>

There could be any number of alerts on a page, depending on what the user does.

What I'd like is to use a jQuery animation to show each of the alert boxes sequentially: once one animation ends, the next one begins.

The answers in that other question said to use a callback like:

$('#Div1').slideDown('fast', function(){
    $('#Div2').slideDown('fast');
});

except that won't work if there's an unknown number of divs to animate. Anyone know of a way to achieve this?

2条回答
Viruses.
2楼-- · 2019-01-24 17:19

It's easy enough to set up:

// Hide all alert DIVs, then show them one at a time
$(function()
{
   var alerts = $(".alert").hide();
   var currentAlert = 0;
   function nextAlert()
   {
      alerts.eq(currentAlert).slideDown('fast', nextAlert);
      ++currentAlert;
   }
   nextAlert();
});

You could probably make a simple plugin method out of this if it's something you'll be using a lot.

查看更多
老娘就宠你
3楼-- · 2019-01-24 17:32

I came up with a solution, though I get a sneaking suspicion that someone who knows more about JS closures might have a few pointers for me.

nextAnim($('.alert'));

function nextAnim($alerts) {
    $alerts
        .eq(0)    // get the first element
        .show("slow",
            function() {
                nextAnim($alerts.slice(1));  // slice off the first element
            }
        )
    ;
}
查看更多
登录 后发表回答