【问题标题】:jQuery .each() - how to iterate over items and animate each of them separately causing ripple effectjQuery .each() - 如何迭代项目并分别为每个项目设置动画,从而产生连锁反应
【发布时间】:2011-06-09 22:41:42
【问题描述】:

我有一个页面,其中有 100 个盒子堆叠在一起,在一个摇摇晃晃的堆栈中。我想用一些 jQuery 动画来模拟这种摇摆不定,让它们在涟漪效应中来回摇摆。

我第一次尝试这个:

$("#teetering-tester").click(function () {
    $("#box-stack div").each(function (id) {
        $(this).animate({ 'margin-right': "+=3px" }, 300 + id, function () {
            $(this).animate({ 'margin-right': "-=3px" }, 300 + id);
        });
    });
    return false;
});

但这会使整个堆栈向右移动,然后向右移动。

我希望能产生连锁反应。所以,我尝试用 setTimeout() 打开新线程:

$("#doTeeter").click(function () {
    $("#output").append("<li>Starting</li>");
    $("#box-stack div").each(function (id) {
        setTimeout($(this).animate({ 'margin-right': "+=3px" }, 300 + id, function () {
            $(this).animate({ 'margin-right': "-=3px" }, 300 + id);
        }), 700, function () {
            $("#output").append("<li>I'm done</li>");
        });
    });
    return false;
});

同样的事情 - 整个堆栈一致移动。

然后我尝试了:

$("#doTeeter").click(function () {
    $("#box-stack div").each(function (id) {
        setTimeout(teeterStack(id), 700);
    });
    return false;
});

... 

function teeterStack(id) {
    $("#box-stack div").eq(id)
        .animate({ 'margin-right': "+=3px" }, 500 + id, function () {
            $(this).animate({ 'margin-right': "-=3px" }, 300 + id);
        });
    });
}

但它们仍然一起移动。

如何在我的 100 个盒子上产生连锁反应?

任何帮助将不胜感激。

谢谢, 斯科特

更新

哦,我刚刚注意到我试图通过使动画持续时间成为 300 毫秒加上项目 ID 的函数来添加一些可变性。

更新 2

我刚试过这个,它有点工作,但有点生涩:

function teeterStack(id) {
    $("#box-stack div").eq(id)
        .animate({ 'margin-right': "+=3px" }, getTime(id), function () {
            $(this).animate({ 'margin-right': "-=3px" }, getTime(id));
        });
}
function getTime(id) {
    var min = 300, max = 2000, step = (max-min)/100;
    return (step*id) + min;
}

但我不知道 delay(),所以我要试一试。

【问题讨论】:

    标签: jquery animation


    【解决方案1】:

    诀窍是根据元素索引延迟效果的开始。这是一个未经测试的戳。注意:使用您的第一个示例。

    $("#teetering-tester").click(function () {
        $("#box-stack div").each(function (id) {
    
            var stallFor = 300 * parseInt(id); // 300 is the gap between delays, tweek it based on visual preference
    
            $(this).delay(stallFor).animate({ 'margin-right': "+=3px" }, function () {
                $(this).animate({ 'margin-right': "-=3px" });
            });
        });
        return false;
    });
    

    建议

    我会使用index 而不是id。变量代表什么令人困惑。

    【讨论】:

      【解决方案2】:

      我认为您对 setTimeout 的想法是正确的,但问题是您使用相同的超时时间值。为 setTimeout 函数的第二个参数提供一个随机(或半随机)值以获得您想要的效果。假设 ID 是序列号,我建议使用 setTimeout(teeterStack(id), 700+(id*100));

      注意:我还没有测试过这个...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        相关资源
        最近更新 更多