发布于:特效 (Effects)

Queue & Dequeue 详解

队列(Queues)是 jQuery 中所有动画的基础,它们允许在元素上异步执行一系列函数。诸如 .slideUp().slideDown().fadeIn().fadeOut() 之类的方法都使用了 .animate(),而后者正是利用了队列来构建一系列步骤,从而在动画持续期间过渡一个或多个 CSS 值。

我们可以向 .animate() 方法传递一个回调函数,该函数将在动画完成后执行。

1
2
3
4
5
6
$( ".box" )
.animate( {
height: 20
}, "slow", function() {
$( "#title" ).html( "We're in the callback, baby!" );
} );

link 队列作为回调

除了将回调作为参数传递之外,我们还可以向队列中添加另一个函数来充当我们的回调。这将在动画的所有步骤完成后执行。

1
2
3
4
5
6
7
8
9
10
$( ".box" )
.animate( {
height: 20
}, "slow")
.queue( function() {
$( "#title" ).html( "We're in the animation, baby!" );
// This tells jQuery to continue to the next item in the queue
$( this ).dequeue();
} );

在这个例子中,入队的函数将在动画结束后立即执行。

jQuery 并不了解队列项如何运行,因此我们需要调用 .dequeue(),它会告诉 jQuery 何时移动到队列中的下一个项目。

另一种出队(dequeuing)的方式是调用传递给回调函数的那个函数。该函数会自动为你调用 .dequeue()

1
2
3
4
.queue( function( next ) {
console.log( "I fired!" );
next();
} );

link 自定义队列

到目前为止,我们所有的动画和队列示例都使用了默认的队列名称 fx。元素可以附加多个队列,我们可以为每个队列赋予不同的名称。我们可以在 .queue() 方法的第一个参数中指定自定义队列名称。

1
2
3
4
5
6
7
8
9
10
$( ".box" )
.queue( "steps", function( next ) {
console.log( "Step 1" );
next();
} )
.queue( "steps", function( next ) {
console.log( "Step 2" );
next();
} )
.dequeue( "steps" );

请注意,我们必须调用 .dequeue() 方法并向其传递自定义队列的名称才能开始执行。除了默认的 fx 之外,每个队列都必须通过调用 .dequeue() 并传递队列名称来手动启动。

link 清空队列

由于队列只是一组有序操作,我们的应用程序中可能存在某些逻辑需要防止剩余的队列条目执行。我们可以通过调用 .clearQueue() 方法来实现,它将清空队列。

1
2
3
4
5
6
7
$( ".box" )
.queue( "steps", function( next ) {
console.log( "Will never log because we clear the queue" );
next();
} )
.clearQueue( "steps" )
.dequeue( "steps" );

在这个例子中,由于我们从 steps 队列中删除了所有内容,因此不会发生任何事情。

清空队列的另一种方法是调用 .stop( true )。这将停止当前正在运行的动画并清空队列。

link 替换队列

当你将一个函数数组作为 .queue() 的第二个参数传递时,该数组将替换原有的队列。

1
2
3
4
5
6
7
8
9
10
11
12
$( ".box" )
.queue( "steps", function( next ) {
console.log( "I will never fire as we totally replace the queue" );
next();
} )
.queue( "steps", [
function( next ) {
console.log( "I fired!" );
next();
}
] )
.dequeue( "steps" );

你也可以在不传递函数的情况下调用 .queue(),这将以数组形式返回该元素的队列。

1
2
3
4
5
6
7
8
$( ".box" ).queue( "steps", function( next ) {
console.log( "I fired!" );
next();
} );
console.log( $( ".box" ).queue( "steps" ) );
$( ".box" ).dequeue( "steps" );