jQuery动画跨多个元素排队

时间:2009-02-02 23:34:01

标签: jquery animation queue

这个问题类似于this one about animation queues,但该主题中的答案非常具体,不易推广。

在我的网络应用程序中,通过输出div class="alert"来向用户报告消息(信息框,错误和警告等),例如:

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

页面上可能有任意数量的警报,具体取决于用户的操作。

我想要的是使用jQuery动画按顺序显示每个警告框:一旦一个动画结束,下一个动画开始。

其他问题的答案说使用回调如:

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

除非在动画中存在未知数量的div,否则无效。有人知道实现这个目标的方法吗?

2 个答案:

答案 0 :(得分:5)

我提出了一个解决方案,但我怀疑有人知道更多关于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
            }
        )
    ;
}

答案 1 :(得分:5)

设置起来非常简单:

// 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();
});

你可能可以制作一个简单的插件方法,如果它是你会经常使用的东西。