亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

jquery隊列queue與原生模仿其實現(xiàn)方法分享

 更新時間:2014年03月25日 16:06:04   作者:  
jquery中的queue和dequeue是一組很有用的方法,他們對于一系列需要按次序運行的函數(shù)特別有用。特別animate動畫,ajax,以及timeout等需要一定時間的函數(shù)

queue() 方法顯示或操作在匹配元素上執(zhí)行的函數(shù)隊列。

queue和dequeue的過程主要是:

用queue把函數(shù)加入隊列(通常是函數(shù)數(shù)組)
用dequeue將函數(shù)數(shù)組中的第一個函數(shù)取出,并執(zhí)行(用shift()方法取出并執(zhí)行)
也就意味著當(dāng)再次執(zhí)行dequeue的時候,得到的是另一個函數(shù)了。同時也意味著,如果不執(zhí)行dequeue,那么隊列中的下一個函數(shù)永遠(yuǎn)不會執(zhí)行。

對于一個元素上執(zhí)行animate方法加動畫,jQuery內(nèi)部也會將其加入名為 fx 的函數(shù)隊列。而對于多個元素要依次執(zhí)行動畫,則必須我們手動設(shè)置隊列進(jìn)行了。

一個例子,要兩個div依次向左移動:

復(fù)制代碼 代碼如下:

<div id="block1">div 1</div>
<div id="block2">div 2</div>
<script type="text/javascript">
 var FUNC=[
  function() {$("#block1").animate({color:"=blue"},aniCB);},
  function() {$("#block2").animate({color:"=red"},aniCB);},
  function() {$("#block1").animate({color:"=yellow"},aniCB);},
  function() {$("#block2").animate({color:"=grey"},aniCB);},
  function() {$("#block1").animate({color:"=green"},aniCB);},
  function(){alert("動畫結(jié)束")}
 ];
 var aniCB=function() {
  $(document).dequeue("myAnimation");
 }
 $(document).queue("myAnimation",FUNC)
 //aniCB();
</script>

我首先建立了一個函數(shù)數(shù)組,里邊是一些列需要依次執(zhí)行的動畫
然后我定義了一個回調(diào)函數(shù),用dequeue方法用來執(zhí)行隊列中的下一個函數(shù)
接著把這個函數(shù)數(shù)組放到document上的myAnimation的隊列中(可以選擇任何元素,我只是為了方便而把這個隊列放在document上)
最后我開始執(zhí)行隊列中的第一個函數(shù)
這樣做的好處在于函數(shù)數(shù)組是線性展開,增減起來非常方便。而且,當(dāng)不要要繼續(xù)進(jìn)行接下來動畫的時候(比如用戶點了某個按鈕),只需要清空那個隊列即可。而要增加更多則只需要加入隊列即可。

復(fù)制代碼 代碼如下:

//清空隊列
$(document).queue("myAnimation",[]);
//加一個新的函數(shù)放在最后
$(document).queue(“myAnimation”,function(){alert("動畫真的結(jié)束了!")});

這當(dāng)然也可以用于ajax之類的方法,如果需要一系列ajax交互,每個ajax都希望在前一個結(jié)束之后開始,之前最原始的方法就是用回調(diào)函數(shù),但這樣太麻煩了。同樣利用queue添加隊列,每次ajax之后的回調(diào)中執(zhí)行一次dequeue即可。

jQuery中動畫animate的隊列實現(xiàn),下面用JavaScript模仿一個:

復(fù)制代碼 代碼如下:

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

相關(guān)文章

最新評論