Reset and loop jquery animation

2019-05-07 02:03发布

I am animating some HTML objects to look like snowflakes falling but am having some trouble on the loop.

Here is my code:

//animation function
function snowflakeAnimate(index) {
    //random numbers
    //time
    var nTime = randomRange(9000,35000);
    var randTime = Math.round(nTime);

    //delay
    var nDelay = randomRange(200,35000);
    var randDelay = Math.round(nDelay);

    $(this).delay(randDelay).animate({
        marginTop: "+600px"
    }, randTime);
};

$(".tweet").each(snowflakeAnimate);

So all it is doing at the moment is animating a snowflake by increasing the top margin to 600. The delay and animation speed are set by generating a random number. My question is how do I reset the snowflake to the top and then run the animation again so it never stops falling.

2条回答
狗以群分
2楼-- · 2019-05-07 02:38

This is how I did it - just had to get the syntax right for the function calling itself...

    function snowflakeAnimate(sfAnimate) {

        //Animation
        $(sfAnimate).addClass("moving").delay(randDelay).animate({
            marginTop: 600
        }, 20000, function() {
            $(sfAnimate).animate({
                marginTop: -150
            }, 0, function() {
                snowflakeAnimate(sfAnimate);
            });
        });
}

So there it is...an infinite loop animation. If you want to see it in action you can check it out at traxmas.realadventure.co.uk

查看更多
可以哭但决不认输i
3楼-- · 2019-05-07 02:49
登录 后发表回答