jQuery动画队列跨多个元素

5
这个问题类似于关于动画队列的问题,但那个帖子中的答案非常具体,不容易概括。
在我的Web应用程序中,通过输出一个class为"alert"的div来向用户报告消息(信息框、错误和警告等)。
<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个回答

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

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

如果这是你会经常使用的功能,你可以将其制作成一个简单的插件方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接