我发现queue()/dequeue()上的jQuery.com文档太简单了,难以理解。jQuery中的队列到底是什么?我该如何使用它们?


当前回答

它允许你排列动画…例如,不是这个

$('#my-element').animate( { opacity: 0.2, width: '100px' }, 2000);

淡入元素,同时使宽度为100px。使用队列允许您呈现动画。所以一个接一个结束。

$("#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();

例子来自http://docs.jquery.com/Effects/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');

这是我已经达到的脚本的简化版本,但应该显示原理-当一个函数添加到队列时,它是使用function构造函数添加的-这样就可以使用循环中的变量动态编写函数。注意函数传递下一个()调用的参数的方式,这是在结束时调用的。本例中的函数没有时间依赖性(它不使用$。fadeIn之类的),所以我使用$.delay来错开帧。

要理解队列方法,您必须了解jQuery如何制作动画。如果你一个接一个地编写多个动画方法调用,jQuery会创建一个“内部”队列,并将这些方法调用添加到队列中。然后它一个接一个地运行这些动画调用。

考虑下面的代码。

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);
}

'queue'/'dequeue'方法让你控制这个'动画队列'。

默认情况下,动画队列名为'fx'。我在这里创建了一个示例页面,其中有各种示例,将说明如何使用队列方法。

http://jsbin.com/zoluge/1/edit?html,output

以上示例页面代码:

$(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);
}

现在你可能会问,我为什么要麻烦这个队列?通常情况下,你不会。但如果你有一个复杂的动画序列,你想控制,那么队列/出队列方法是你的朋友。

也可以在jQuery组中看到关于创建复杂动画序列的有趣对话。

http://groups.google.com/group/jquery-en/browse_thread/thread/b398ad505a9b0512/f4f3e841eab5f5a2?lnk=gst

动画演示:

http://www.exfer.net/test/jquery/tabslide/

如果你还有问题,请告诉我。

它允许你排列动画…例如,不是这个

$('#my-element').animate( { opacity: 0.2, width: '100px' }, 2000);

淡入元素,同时使宽度为100px。使用队列允许您呈现动画。所以一个接一个结束。

$("#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();

例子来自http://docs.jquery.com/Effects/queue

jQuery .queue()和.dequeue()的使用

jQuery中的队列用于动画。你可以把它们用于任何你喜欢的目的。它们是使用jQuery.data()以每个元素为基础存储的函数数组。先进先出(FIFO)。您可以通过调用.queue()向队列中添加函数,并使用.dequeue()(通过调用)删除函数。

为了理解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 );
  });
};

默认队列- fx

jQuery的默认队列是fx。默认队列具有一些不与其他队列共享的特殊属性。

自动启动:当调用$(elem).queue(function(){});fx队列将自动退出下一个函数的队列,并在队列尚未启动时运行它。 'inprogress'哨兵:每当你从fx队列中dequeue()一个函数时,它将unshift()(推入数组的第一个位置)字符串"inprogress" -这标志着队列当前正在运行。 这是默认的!fx队列由.animate()和所有默认调用它的函数使用。

注意:如果你正在使用一个自定义队列,你必须手动.dequeue()函数,他们不会自动启动!

检索/设置队列

可以通过调用.queue()而不带函数参数来检索对jQuery队列的引用。如果您想查看队列中有多少项,可以使用该方法。你可以使用push, pop, unshift, shift来操作队列。您可以通过向.queue()函数传递一个数组来替换整个队列。

快速的例子:

// 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)); 

一个动画队列的例子:

在jsFiddle上运行示例

$(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);
});

另一个自定义队列示例

在jsFiddle上运行示例

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');

排队Ajax调用:

我开发了一个使用$. ajaxqueue()插件。Deferred、.queue()和$.ajax()也传递回一个承诺,该承诺在请求完成时被解析。另一个版本的$。在1.4中仍然有效的ajaxQueue张贴在我对Ajax请求排序的回答上

/*
* 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);

我现在把这篇文章添加到learn.jquery.com上,那个网站上还有其他关于队列的好文章,去看看吧。

队列中的多个对象动画

下面是一个简单的队列中多对象动画的例子。

Jquery允许我们只对一个对象进行队列处理。但是在动画函数中,我们可以访问其他对象。在这个例子中,我们在#box1和#box2对象上创建队列。

可以把队列看作一个函数数组。你可以把queue当作数组来操作。你可以使用push, pop, unshift, shift来操作队列。在这个例子中,我们从动画队列中移除最后一个函数,并将其插入到开头。

完成后,通过dequeue()函数启动动画队列。

参见jsFiddle

html:

  <button id="show">Start Animation Queue</button>
  <p></p>
  <div id="box1"></div>
  <div id="box2"></div>
  <div id="q"></div>

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:

        #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; }