什么是 jQuery 中的队列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1058158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are queues in jQuery?
提问by jquerynewbie
I found the jQuery.com document on queue()
/dequeue()
is too simple to understand. What exactly are queues in jQuery? How should I use them?
我发现queue()
/上的 jQuery.com 文档dequeue()
太简单了,难以理解。jQuery 中的队列到底是什么?我应该如何使用它们?
回答by gnarf
The uses of jQuery .queue()
and .dequeue()
jQuery 的使用.queue()
和.dequeue()
Queuesin jQuery are used for animations. You can use them for any purpose you like. They are an array of functionsstored on a per element basis, using jQuery.data()
. They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue()
, and you remove (by calling) the functions using .dequeue()
.
jQuery 中的队列用于动画。您可以将它们用于您喜欢的任何目的。它们是基于每个元素存储的函数数组,使用jQuery.data()
. 它们是先进先出 (FIFO)。您可以通过调用将函数添加到队列中.queue()
,并使用 删除(通过调用)函数.dequeue()
。
To understand the internal jQuery queue functions, reading the sourceand looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .delay()
:
要了解内部 jQuery 队列函数,阅读源代码并查看示例对我有很大帮助。我见过的队列函数的最佳示例之一是.delay()
:
$.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
};
The default queue - fx
默认队列 - fx
The default queue in jQuery is fx
. The default queue has some special properties that are not shared with other queues.
jQuery 中的默认队列是fx
. 默认队列有一些不与其他队列共享的特殊属性。
- Auto Start:When calling
$(elem).queue(function(){});
thefx
queue will automaticallydequeue
the next function and run it if the queue hasn't started. - 'inprogress' sentinel:Whenever you
dequeue()
a function from thefx
queue, it willunshift()
(push into the first location of the array) the string"inprogress"
- which flags that the queue is currently being run. - It's the default!The
fx
queue is used by.animate()
and all functions that call it by default.
- 自动启动:当调用
$(elem).queue(function(){});
的fx
队列将自动dequeue
在下一个功能,并运行它,如果队列尚未开始。 - 'inprogress' sentinel:每当您
dequeue()
从fx
队列中调用一个函数时,它都会unshift()
(推入数组的第一个位置)字符串"inprogress"
- 标记队列当前正在运行。 - 这是默认的!该
fx
队列由使用.animate()
和默认调用它的所有功能。
NOTE:If you are using a custom queue, you must manually .dequeue()
the functions, they will not auto start!
注意:如果您使用自定义队列,则必须手动执行.dequeue()
这些功能,它们不会自动启动!
Retrieving/Setting the queue
检索/设置队列
You can retrieve a reference to a jQuery queue by calling .queue()
without a function argument. You can use the method if you want to see how many items are in the queue. You can use push
, pop
, unshift
, shift
to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue()
function.
您可以通过.queue()
不带函数参数的调用来检索对 jQuery 队列的引用。如果您想查看队列中有多少项目,可以使用该方法。您可以使用push
, pop
, unshift
,shift
来操作队列。您可以通过将数组传递给.queue()
函数来替换整个队列。
Quick Examples:
快速示例:
// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop();
// insert it at the beginning:
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3));
An animation (fx
) queue example:
动画 ( fx
) 队列示例:
$(function() {
// lets do something with google maps:
var $map = $("#map_canvas");
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map($map[0], myOptions);
var resized = function() {
// simple animation callback - let maps know we resized
google.maps.event.trigger(map, 'resize');
};
// wait 2 seconds
$map.delay(2000);
// resize the div:
$map.animate({
width: 250,
height: 250,
marginLeft: 250,
marginTop:250
}, resized);
// geocode something
$map.queue(function(next) {
// find stackoverflow's whois address:
geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);
function handleResponse(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
map.setZoom(13);
map.setCenter(location);
new google.maps.Marker({ map: map, position: location });
}
// geocoder result returned, continue with animations:
next();
}
});
// after we find stack overflow, wait 3 more seconds
$map.delay(3000);
// and resize the map again
$map.animate({
width: 500,
height: 500,
marginLeft:0,
marginTop: 0
}, resized);
});
Another custom queue example
另一个自定义队列示例
var theQueue = $({}); // jQuery on an empty object - a perfect queue holder
$.each([1,2,3],function(i, num) {
// lets add some really simple functions to a queue:
theQueue.queue('alerts', function(next) {
// show something, and if they hit "yes", run the next function.
if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
next();
}
});
});
// create a button to run the queue:
$("<button>", {
text: 'Run Queue',
click: function() {
theQueue.dequeue('alerts');
}
}).appendTo('body');
// create a button to show the length:
$("<button>", {
text: 'Show Length',
click: function() {
alert(theQueue.queue('alerts').length);
}
}).appendTo('body');
Queueing Ajax Calls:
排队 Ajax 调用:
I developed an $.ajaxQueue()
plugin that uses the $.Deferred
, .queue()
, and $.ajax()
to also pass back a promisethat is resolved when the request completes. Another version of $.ajaxQueue
that still works in 1.4 is posted on my answer to Sequencing Ajax Requests
我开发了一个$.ajaxQueue()
插件,它使用$.Deferred
, .queue()
, 并且$.ajax()
还传回在请求完成时解决的承诺。$.ajaxQueue
在 1.4 中仍然有效的另一个版本发布在我对Sequencing Ajax Requests 的回答中
/*
* jQuery.ajaxQueue - A queue for ajax requests
*
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/
(function($) {
// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});
$.ajaxQueue = function( ajaxOpts ) {
var jqXHR,
dfd = $.Deferred(),
promise = dfd.promise();
// queue our ajax request
ajaxQueue.queue( doRequest );
// add the abort method
promise.abort = function( statusText ) {
// proxy abort to the jqXHR if it is active
if ( jqXHR ) {
return jqXHR.abort( statusText );
}
// if there wasn't already a jqXHR we need to remove from queue
var queue = ajaxQueue.queue(),
index = $.inArray( doRequest, queue );
if ( index > -1 ) {
queue.splice( index, 1 );
}
// and then reject the deferred
dfd.rejectWith( ajaxOpts.context || ajaxOpts,
[ promise, statusText, "" ] );
return promise;
};
// run the actual query
function doRequest( next ) {
jqXHR = $.ajax( ajaxOpts )
.done( dfd.resolve )
.fail( dfd.reject )
.then( next, next );
}
return promise;
};
})(jQuery);
I have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.
我现在已将此添加为一篇关于learn.jquery.com 的文章,该站点上还有其他关于队列的精彩文章,去看看吧。
回答by SolutionYogi
To understand queue method, you have to understand how jQuery does animation. If you write multiple animate method calls one after the other, jQuery creates an 'internal' queue and adds these method calls to it. Then it runs those animate calls one by one.
要了解队列方法,您必须了解 jQuery 是如何做动画的。如果您一个接一个地编写多个动画方法调用,jQuery 会创建一个“内部”队列并将这些方法调用添加到其中。然后它会一一运行那些动画调用。
Consider following code.
考虑以下代码。
function nonStopAnimation()
{
//These multiple animate calls are queued to run one after
//the other by jQuery.
//This is the reason that nonStopAnimation method will return immeidately
//after queuing these calls.
$('#box').animate({ left: '+=500'}, 4000);
$('#box').animate({ top: '+=500'}, 4000);
$('#box').animate({ left: '-=500'}, 4000);
//By calling the same function at the end of last animation, we can
//create non stop animation.
$('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}
The 'queue'/'dequeue' method gives you control over this 'animation queue'.
'queue'/'dequeue' 方法让您可以控制这个“动画队列”。
By default the animation queue is named 'fx'. I have created a sample page here which has various examples which will illustrate how the queue method could be used.
默认情况下,动画队列被命名为“fx”。我在这里创建了一个示例页面,其中包含各种示例,这些示例将说明如何使用队列方法。
http://jsbin.com/zoluge/1/edit?html,output
http://jsbin.com/zoluge/1/edit?html,输出
Code for above sample page:
以上示例页面的代码:
$(document).ready(function() {
$('#nonStopAnimation').click(nonStopAnimation);
$('#stopAnimationQueue').click(function() {
//By default all animation for particular 'selector'
//are queued in queue named 'fx'.
//By clearning that queue, you can stop the animation.
$('#box').queue('fx', []);
});
$('#addAnimation').click(function() {
$('#box').queue(function() {
$(this).animate({ height : '-=25'}, 2000);
//De-queue our newly queued function so that queues
//can keep running.
$(this).dequeue();
});
});
$('#stopAnimation').click(function() {
$('#box').stop();
});
setInterval(function() {
$('#currentQueueLength').html(
'Current Animation Queue Length for #box ' +
$('#box').queue('fx').length
);
}, 2000);
});
function nonStopAnimation()
{
//These multiple animate calls are queued to run one after
//the other by jQuery.
$('#box').animate({ left: '+=500'}, 4000);
$('#box').animate({ top: '+=500'}, 4000);
$('#box').animate({ left: '-=500'}, 4000);
$('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}
Now you may ask, why should I bother with this queue? Normally, you wont. But if you have a complicated animation sequence which you want to control, then queue/dequeue methods are your friend.
现在你可能会问,我为什么要打扰这个队列?通常,你不会。但是如果你有一个复杂的动画序列想要控制,那么队列/出队方法就是你的朋友。
Also see this interesting conversation on jQuery group about creating a complicated animation sequence.
另请参阅 jQuery 组上有关创建复杂动画序列的有趣对话。
Demo of the animation:
动画演示:
http://www.exfer.net/test/jquery/tabslide/
http://www.exfer.net/test/jquery/tabslide/
Let me know if you still have questions.
如果您还有问题,请告诉我。
回答by enf644
Multiple objects animation in a queue
队列中的多个对象动画
Here is a simple example of multiple objects animation in a queue.
这是队列中多个对象动画的简单示例。
Jquery alow us to make queue over only one object. But within animation function we can access other objects. In this example we build our queue over #q object while animating #box1 and #box2 objects.
Jquery 允许我们只对一个对象进行排队。但是在动画函数中,我们可以访问其他对象。在这个例子中,我们在#q 对象上构建队列,同时为#box1 和#box2 对象设置动画。
Think of queue as a array of functions. So you can manipulate queue as a array. You can use push, pop, unshift, shift to manipulate the queue. In this example we remove the last function from the animation queue and insert it at the beginning.
将队列视为一组函数。因此,您可以将队列作为数组进行操作。您可以使用 push、pop、unshift、shift 来操作队列。在本例中,我们从动画队列中移除最后一个函数并将其插入到开头。
When we are done, we start animation queue by dequeue() function.
完成后,我们通过 dequeue() 函数启动动画队列。
html:
html:
<button id="show">Start Animation Queue</button>
<p></p>
<div id="box1"></div>
<div id="box2"></div>
<div id="q"></div>
js:
js:
$(function(){
$('#q').queue('chain',function(next){
$("#box2").show("slow", next);
});
$('#q').queue('chain',function(next){
$('#box1').animate(
{left: 60}, {duration:1000, queue:false, complete: next}
)
});
$('#q').queue('chain',function(next){
$("#box1").animate({top:'200'},1500, next);
});
$('#q').queue('chain',function(next){
$("#box2").animate({top:'200'},1500, next);
});
$('#q').queue('chain',function(next){
$("#box2").animate({left:'200'},1500, next);
});
//notice that show effect comes last
$('#q').queue('chain',function(next){
$("#box1").show("slow", next);
});
});
$("#show").click(function () {
$("p").text("Queue length is: " + $('#q').queue("chain").length);
// remove the last function from the animation queue.
var lastFunc = $('#q').queue("chain").pop();
// insert it at the beginning:
$('#q').queue("chain").unshift(lastFunc);
//start animation queue
$('#q').dequeue('chain');
});
css:
css:
#box1 { margin:3px; width:40px; height:40px;
position:absolute; left:10px; top:60px;
background:green; display: none; }
#box2 { margin:3px; width:40px; height:40px;
position:absolute; left:100px; top:60px;
background:red; display: none; }
p { color:red; }
回答by alex
It allows you to queue up animations... for example, instead of this
它允许你排队动画......例如,而不是这个
$('#my-element').animate( { opacity: 0.2, width: '100px' }, 2000);
Which fades the element and makes the width 100 px at the same time. Using the queue allows you to stage the animations. So one finishes after the other.
其衰要素,将宽度100像素在同一时间。使用队列可以让您暂存动画。所以一个接一个完成。
$("#show").click(function () {
var n = $("div").queue("fx");
$("span").text("Queue length is: " + n.length);
});
function runIt() {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
$("div").slideToggle(1000);
$("div").slideToggle("fast");
$("div").animate({left:'-=200'},1500);
$("div").hide("slow");
$("div").show(1200);
$("div").slideUp("normal", runIt);
}
runIt();
Example from http://docs.jquery.com/Effects/queue
回答by bjorsq
This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:
这个线程对我的问题有很大帮助,但我以不同的方式使用了 $.queue 并认为我会在这里发布我想出的东西。我需要的是要触发的一系列事件(帧),但要动态构建该序列。我有可变数量的占位符,每个占位符都应该包含一个动画图像序列。数据保存在一个数组数组中,所以我遍历数组来为每个占位符构建每个序列,如下所示:
/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
for (var l = 0; l < ph[i].length; l++) {
/* create a function which swaps an image, and calls the next function in the queue */
theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
/* set the animation speed */
theQueue.delay(200,'anim');
}
}
/* start the animation */
theQueue.dequeue('anim');
This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.
这是我到达的脚本的简化版本,但应该显示原理 - 当一个函数添加到队列时,它是使用 Function 构造函数添加的 - 这样可以使用循环中的变量动态编写函数( s)。注意函数传递 next() 调用参数的方式, this 在最后被调用。这种情况下的函数没有时间依赖性(它不使用 $.fadeIn 或类似的东西),所以我使用 $.delay 交错帧。
回答by ardsrk
Function makeRed
and makeBlack
use queue
and dequeue
to execute each other. The effect is that, the '#wow' element blinks continuously.
功能makeRed
以及makeBlack
使用queue
和dequeue
执行对方。效果是,'#wow' 元素不断闪烁。
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#wow').click(function(){
$(this).delay(200).queue(makeRed);
});
});
function makeRed(){
$('#wow').css('color', 'red');
$('#wow').delay(200).queue(makeBlack);
$('#wow').dequeue();
}
function makeBlack(){
$('#wow').css('color', 'black');
$('#wow').delay(200).queue(makeRed);
$('#wow').dequeue();
}
</script>
</head>
<body>
<div id="wow"><p>wow</p></div>
</body>
</html>