发布在:效果

队列和出列说明

队列是 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 何时移至队列中的下一项。

出列的另一种方法是调用传递给回调的函数。该函数将自动为您调用 .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" );