Home  >  Article  >  Web Front-end  >  jquery队列queue与原生模仿其实现方法分享_jquery

jquery队列queue与原生模仿其实现方法分享_jquery

WBOY
WBOYOriginal
2016-05-16 16:54:44835browse

queue() 方法显示或操作在匹配元素上执行的函数队列。

queue和dequeue的过程主要是:

用queue把函数加入队列(通常是函数数组)
用dequeue将函数数组中的第一个函数取出,并执行(用shift()方法取出并执行)
也就意味着当再次执行dequeue的时候,得到的是另一个函数了。同时也意味着,如果不执行dequeue,那么队列中的下一个函数永远不会执行。

对于一个元素上执行animate方法加动画,jQuery内部也会将其加入名为 fx 的函数队列。而对于多个元素要依次执行动画,则必须我们手动设置队列进行了。

一个例子,要两个div依次向左移动:

复制代码 代码如下:

div 1

div 2


我首先建立了一个函数数组,里边是一些列需要依次执行的动画
然后我定义了一个回调函数,用dequeue方法用来执行队列中的下一个函数
接着把这个函数数组放到document上的myAnimation的队列中(可以选择任何元素,我只是为了方便而把这个队列放在document上)
最后我开始执行队列中的第一个函数
这样做的好处在于函数数组是线性展开,增减起来非常方便。而且,当不要要继续进行接下来动画的时候(比如用户点了某个按钮),只需要清空那个队列即可。而要增加更多则只需要加入队列即可。

复制代码 代码如下:

//清空队列
$(document).queue("myAnimation",[]);
//加一个新的函数放在最后
$(document).queue(“myAnimation”,function(){alert("动画真的结束了!")});

这当然也可以用于ajax之类的方法,如果需要一系列ajax交互,每个ajax都希望在前一个结束之后开始,之前最原始的方法就是用回调函数,但这样太麻烦了。同样利用queue添加队列,每次ajax之后的回调中执行一次dequeue即可。

jQuery中动画animate的队列实现,下面用JavaScript模仿一个:

复制代码 代码如下:

function Queue(){
 this.a = [];
 this.t = null;
}
Queue.prototype = {
 queue:function(s){
  var self = this;
  this.a.push(s);
  this.hold();
  return this;
 },
 hold:function(){
  var self = this;
  clearTimeout(this.t);
  this.t = setTimeout(function(){
   console.log("Queue start! ",self.a);
   self.dequeue();
  },0);
 },
 dequeue:function(){
  var s = this.a.shift(),self = this;
  if(s){
   console.log("s:"+s);
   setTimeout(function(){
    console.log("end:"+s);
    self.dequeue();
   },s);
  }
 }
};
var a = new Queue().queue(500).queue(200).queue(400).queue(1500).queue(300).queue(2000);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn