jQuery动画跨多个元素队列

时间:2021-09-20 14:27:15

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:

在我的web应用程序中,通过输出class="alert"的div将消息反馈给用户(信息框、错误和警告等):

<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.

我想使用jQuery动画来依次显示每个警告框:一个动画结束后,下一个动画开始。

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?

但是,如果有数量未知的divs要制作动画,那就行不通了。有人知道实现这个目标的方法吗?

2 个解决方案

#1


5  

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.

我想出了一个解决方案,不过我偷偷地怀疑,了解JS闭包更多的人可能会给我一些建议。

nextAnim($('.alert'));

function nextAnim($alerts) {
    $alerts
        .eq(0)    // get the first element
        .show("slow",
            function() {
                nextAnim($alerts.slice(1));  // slice off the first element
            }
        )
    ;
}

#2


5  

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.

如果你经常使用它,你可以用它来做一个简单的插件方法。

#1


5  

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.

我想出了一个解决方案,不过我偷偷地怀疑,了解JS闭包更多的人可能会给我一些建议。

nextAnim($('.alert'));

function nextAnim($alerts) {
    $alerts
        .eq(0)    // get the first element
        .show("slow",
            function() {
                nextAnim($alerts.slice(1));  // slice off the first element
            }
        )
    ;
}

#2


5  

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.

如果你经常使用它,你可以用它来做一个简单的插件方法。