在jQuery中重复嵌套动画

时间:2013-08-21 15:01:55

标签: jquery animation jquery-animate

我有一个动画(一个带有背景图像的div),它有另一个动画作为回调。

汽车从右向左行驶,然后转弯并向后行驶。都有一些延迟。我希望整个动画再次无限次运行。

以下是代码:

var tempoPolente = 10000;
var viewport = $(window).width() + 300;

// Animation 
var polenteAnim = function() { 
    $("#polente").removeClass('flip').animate({"right": "+="+viewport}, tempoPolente, 'linear',
            function() {
                setTimeout(function() {
                    $("#polente").addClass("flip").animate({"right": "-="+viewport}, tempoPolente, 'linear');
                }, 1000);
    });
}; 

2 个答案:

答案 0 :(得分:1)

稍微修改linked example,您可以使用$.delay在动画中引入延迟:

这是最简单的形式,但确实会在动画开始时引入延迟:

Demo

function loop() {
    $('.bouncer').delay(1000)
                 .animate({'top': '500'}, 1000)
                 .delay(1000)
                 .animate({top: 0}, 1000, loop);
}
loop();

要删除该延迟,请使用setTimeout替换上一个完成回调并删除初始延迟:

Demo

function loop() {
    $('.bouncer').animate({'top': '500'}, 1000)
                 .delay(1000)
                 .animate({top: 0}, 1000, function() {
                     setTimeout(loop, 1000);
                 });
}
loop();
修改为使用此样式的

您的函数类似于:

var polenteAnim = function() { 
    $("#polente").removeClass('flip')
                 .animate({"right": "+="+viewport}, tempoPolente, 'linear')
                 .delay(1000)
                 .addClass("flip")
                 .animate({"right": "-="+viewport}, tempoPolente, 'linear', function() {
                     setTimeout(polenteAnim, 1000);
                 });
}; 

如果您希望保持动画功能不变,只需在完成内部动画后再次调用入口点:

var polenteAnim = function() { 
    $("#polente").removeClass('flip').animate({"right": "+="+viewport}, tempoPolente, 'linear',
            function() {
                setTimeout(function() {
                    // Add polente as the completion callback here...
                    $("#polente").addClass("flip").animate({"right": "-=" + viewport}, tempoPolente, 'linear', function () {
                        setTimeout(polenteAnim, 1000);
                    });
                }, 1000);
    });
}; 

答案 1 :(得分:0)

我认为一个简单的 recursion 足以做无限循环。

试试这个。

var tempoPolente = 10000;
var viewport = $(window).width() + 300;

// Animation 
var polenteAnim = function() { 
    $("#polente").removeClass('flip').animate({"right": "+="+viewport}, tempoPolente, 'linear',
            function() {
                setTimeout(function() {
                    $("#polente").addClass("flip").animate({"right": "-="+viewport}, tempoPolente, 'linear');
                }, 1000);
    });
polenteAnim();  //recursion
};