问题
I have an animation (a div with a background image) which has another animation as callback.
A car drives from right to left, then turns and drives back. all with some delay. I want the whole animation run again infinite times.
Here is the code:
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);
});
};
回答1:
Modifying the linked example slightly, you can introduce delays into your animation using $.delay:
This is the simplest form, but does introduce a delay at the start of the animation:
Demo
function loop() {
$('.bouncer').delay(1000)
.animate({'top': '500'}, 1000)
.delay(1000)
.animate({top: 0}, 1000, loop);
}
loop();
To remove that delay, replace the last completion callback with a setTimeout and remove the initial delay:
Demo
function loop() {
$('.bouncer').animate({'top': '500'}, 1000)
.delay(1000)
.animate({top: 0}, 1000, function() {
setTimeout(loop, 1000);
});
}
loop();
Your Function modified to use this style would look something like:
var polenteAnim = function() {
$("#polente").removeClass('flip')
.animate({"right": "+="+viewport}, tempoPolente, 'linear')
.delay(1000)
.addClass("flip")
.animate({"right": "-="+viewport}, tempoPolente, 'linear', function() {
setTimeout(polenteAnim, 1000);
});
};
If you prefer to leave your animation function intact, you can simply call the entry point again on completion of the internal animation:
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:
I think a simple recursion is enough to do infinite loops.
Try this.
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
};
来源:https://stackoverflow.com/questions/18360963/repeating-a-nested-animation-in-jquery