jQuery中的非嵌套动画序列?

983*_*875 6 javascript queue jquery animation sequence

我正在尝试使用jQuery创建一个动画序列,其中一个动画在前一个动画完成后开始.但我无法绕过它.我试图使用jQuery.queue,但我认为我不能使用它,因为它似乎为jQuery数组中的每个元素都有一个单独的队列.

我需要这样的东西:

$('li.some').each(function(){
    // Add to queue
    $(this).animate({ width: '+=100' }, 'fast', function(){
        // Remove from queue
        // Start next animation
    });
});
Run Code Online (Sandbox Code Playgroud)

是否有jQuery方法可以执行此操作,还是必须手动编写和处理自己的队列?

Gab*_*oli 18

你可以做一个自定义,.queue()以避免无限的嵌套..

var q = $({});

function animToQueue(theQueue, selector, animationprops) {
    theQueue.queue(function(next) {
        $(selector).animate(animationprops, next);
    });
}

// usage
animToQueue(q, '#first', {width: '+=100'});
animToQueue(q, '#second', {height: '+=100'});
animToQueue(q, '#second', {width: '-=50'});
animToQueue(q, '#first', {height: '-=50'});
Run Code Online (Sandbox Code Playgroud)

演示http://jsfiddle.net/gaby/qDbRm/2/


另一方面,如果你想要一个接一个地为多个元素执行相同的动画,那么你可以.delay()在所有之前的元素的持续时间内使用它们的索引到每个元素的动画.

$('li.some').each(function(idx){
    var duration = 500; 
    $(this).delay(duration*idx).animate({ width: '+=100' }, duration);
});
Run Code Online (Sandbox Code Playgroud)

演示http://jsfiddle.net/gaby/qDbRm/3/