【问题标题】:How to loop an animation for multiple appended divs?如何为多个附加的 div 循环动画?
【发布时间】:2013-09-20 17:43:14
【问题描述】:

我用 jquery 制作了一个 div 动画。

循环是这样的:向右,然后向下,向左,再向下。

当按下开始按钮时,第一个 div 开始动画循环。下一个 div 以随机间隔附加,下一个 div 相同,依此类推。 但是当添加第二个 div 时,整个动画循环就会变得疯狂。

我想要完成的工作: 如果附加了第二个 div,第一个应该只是完成它的动画循环。 第二个和之后的也完成了他们的循环。

你能帮我解决这个问题吗?我应该为课程添加计数器还是什么?

(顺便说一下我在这个jsfiddle中禁用了随机附加代码,所以你可以先看到正确的动画循环。请启用以查看疯狂效果)

Demo

HTML

<div id="arena">
    <div id="start">start</div>
</div>

jQuery

var counter = 0;

$("#start").on('click', function () {
    $("#arena").append('<div class="b"></div>');
    bbLoop();
    $("#start").hide();
});

function bbLoop() {
    bbRight();
}

function bbLeft() {
    $(".b").animate({
        left: "-=300"
    }, 1500, "swing", bbLeftDown);
}

function bbRight() {
    $(".b").animate({
        left: "+=300"
    }, 1500, "swing", bbRightDown);
}

function bbLeftDown() {
    $(".b").animate({
        bottom: "-=30"
    }, 300, "swing", bbRight);
}

function bbRightDown() {
    $(".b").animate({
        bottom: "-=30"
    }, 300, "swing", bbLeft);
}

/*

function doSomething() {}

(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(function () {
        doSomething();
    $("#arena").append('<div class="b"></div>');
        loop();
    }, rand);
}());
*/

【问题讨论】:

    标签: loops html jquery-animate append


    【解决方案1】:

    Try this

    它利用通过每个函数传递相同的对象,以便附加元素可以与第一个元素分开动画

    $("#start").on('click', function () {
        $("#arena").append('<div class="b"></div>');
        bbLoop($('.b:eq(0)'));
        $("#start").hide();
    
        (function loop() {
            var rand = Math.round(Math.random() * (3000 - 500)) + 500;
            setTimeout(function () {
                var elem = $('<div class="b"></div>');
                $("#arena").append(elem);
                bbRight(elem);
                doSomething();
                loop();
            }, rand);
        }());
    });
    
    function bbLoop(obj) {
        bbRight(obj);
    }
    
    function bbLeft(obj) {
        obj.animate({
            left: "-=300"
        }, 1500, "swing", bbLeftDown(obj));
    }
    
    function bbRight(obj) {
        obj.animate({
            left: "+=300"
        }, 1500, "swing", function() { bbRightDown(obj) });
    }
    
    function bbLeftDown(obj) {
        obj.animate({
            top: "+=300"
        }, 300, "swing");
    }
    
    function bbRightDown(obj) {
        obj.animate({
            top: "+=300"
        }, 300, "swing", bbLeft(obj));
    }
    
    
    
    function doSomething() {}
    

    或者,如果您希望在最后删除它们,check here.animate 有时会以古怪的方式工作,因此setTimeout 中的结束动画时间的近似值是必要的

    【讨论】:

    • 对不起,我的反应迟了,我试图理解代码。这正是我想要的,所以非常感谢。我只是要再分析一下代码! :)
    • 如果有任何需要我进一步解释的部分,请告诉我
    猜你喜欢
    • 2021-12-21
    • 2017-05-26
    • 2012-11-02
    • 2016-07-16
    • 2013-03-20
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多