jQuery .each() - 如何迭代项目并分别为它们设置动画,从而产生连锁反应

Sco*_*ott 1 jquery animation

我有一个页面,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;
});
Run Code Online (Sandbox Code Playgroud)

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

我希望有涟漪效应.所以,我尝试用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;
});
Run Code Online (Sandbox Code Playgroud)

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

然后我尝试了:

$("#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);
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

但他们仍然在一起.

如何在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;
}
Run Code Online (Sandbox Code Playgroud)

但是我不知道延迟()所以我要给它一个机会.

nat*_*lds 9

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

$("#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;
});
Run Code Online (Sandbox Code Playgroud)

建议

我用index而不是id.关于变量代表什么令人困惑.