【问题标题】:Repeating a nested animation in jQuery在 jQuery 中重复嵌套动画
【发布时间】:2013-08-21 15:01:55
【问题描述】:

我有一个动画(带有背景图像的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);
    });
}; 

【问题讨论】:

标签: jquery animation jquery-animate


【解决方案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);
    });
}; 

【讨论】:

    【解决方案2】:

    我认为一个简单的 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
    }; 
    

    【讨论】:

      猜你喜欢
      • 2014-09-03
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多