jQuery .animate / .each chaining

问题描述 投票:0回答:5

我正在尝试将匹配的东西组合起来:

$(".item").each(function(i) {
    //animation here
});

使用jQuery固有的链接功能,强制动画等待上一个动画完成,例如:

$(".item").each(function(i) {
    $(this).animate({marginLeft:"0"}, 60);
});

然后在动画完成后触发.load函数。基本上,我想按顺序淡出四个项目[一个接一个,而不是一次全部],然后将四个新项目加载到同一个div中,替换前四个。

我怎样才能以可重用/可变的方式做到这一点?

jquery jquery-animate jquery-chaining
5个回答
5
投票

如何检查元素是否是最后一个然后添加回调?

$(".item").each(function(i, elem) {
    var callback = $(elem).is(':last') ? function() {
        //dosomething
    } : function(){};
    $(this).animate({marginLeft:"0"}, {duration: 60, complete: callback);
});

4
投票

只需指定动画的回调并跟踪已淡出的项目数。然后,当它们全部完成后,删除它们并添加新的。

var items = $('.item');
var parent = items.parent();
var itemCount = items.length;
items.each(function()
{
    $(this).fadeOut('medium', function()
    {
        itemCount--;
        if (itemCount == 0)
        {
            // Remove the items and add the new ones.
            items.remove();
            parent.append('...')
        }
    });
});

2
投票
$("#more:not(.disabled)").live("click", function(event) {
    event.preventDefault();

    var urlPieces = (event.target.href).split("/");
    var nextURL = urlPieces[urlPieces.length - 2] + "/" + urlPieces[urlPieces.length - 1];
    var items = $(".item");
    var itemCount = items.length;   

    items.each(function(i) {
        var passthru = this;
        window.setTimeout(function() {
            $(passthru).animate({opacity:"0"}, 60, function() {
                if (i == itemCount - 1) {
                    $("#browse").load(nextURL + " .item, #controls", fadeInNew);
                }
            });
        }, 60*i);
    });
});

fadeInNew在其他地方处理新的逐个淡入淡出,但这是我正在寻找或多或少的一些额外的代码围绕它可能揭示正在发生的事情(在它的href中有一个url的下一个箭头) ,如果javascript打开,我需要下一页相对于当前的URL,如果它关闭,它会跟随该url作为href并加载一个新页面,该页面在页面上具有相同的内容,除了新的项目已经$ .load-ed。


0
投票

只需像这样更新延迟:

$(".item").each(function(i) {
    $(this).delay(200*i).animate({marginLeft:"0"}, 60);
});
ul li.item {
  margin-left: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="item">List 1</li>
  <li class="item">List 2</li>
  <li class="item">List 3</li>
  <li class="item">List 4</li>
  <li class="item">List 5</li>
  <li class="item">List 6</li>
</ul>

0
投票

我的贡献,基于@david-hellsing算法:)

function pop_in(array_elem, index) {
    $(array_elem[index]).animate({
        width: 'toggle',
        height: 'toggle'
    }, 700)// callback will be a promise
    .promise()
    .then(() => {
        $(array_elem[index]).css({visibility: 'hidden'}); //hide after reduce size

        if(index > 0)
            pop_in(array_elem, --index) //recursive call
        else
            console.log("Animation finished. Execute another function from here.");
    });
}
const items_menu = $(".item");
pop_in(items_menu, items_menu.length-1); //start from last to first element

请注意,您可以根据自己的目的更改宽度和高度属性。

© www.soinside.com 2019 - 2024. All rights reserved.