JQuery隊列queue與原生模仿其實現

來源:互聯網
上載者:User

標籤:http   io   color   ar   java   div   on   art   log   

jQuery中的queue和dequeue是一組很有用的方法,他們對於一系列需要按次序啟動並執行函數特別有用。特別animate動畫,ajax,以及timeout等需要一定時間的函數。

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

queue和dequeue的過程主要是:

  1. 用queue把函數排入佇列(通常是函數數組)惠民縣宿哲服裝
  2. 用dequeue將函數數組中的第一個函數取出,並執行(用shift()方法取出並執行)

也就意味著當再次執行dequeue的時候,得到的是另一個函數了。同時也意味著,如果不執行dequeue,那麼隊列中的下一個函數永遠不會執行。

對於一個元素上執行animate方法加動畫,jQuery內部也會將其加入名為 fx 的函數隊列。而對於多個元素要依次執行動畫,則必須我們手動設定隊列進行了。

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

<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("動畫結束")}];var aniCB=function() {$(document).dequeue("myAnimation");}$(document).queue("myAnimation",FUNC)//aniCB();</script>
  1. 我首先建立了一個函數數組,裡邊是一些列需要依次執行的動畫
  2. 然後我定義了一個回呼函數,用dequeue方法用來執行隊列中的下一個函數
  3. 接著把這個函數數組放到document上的myAnimation的隊列中(可以選擇任何元素,我只是為了方便而把這個隊列放在document上)
  4. 最後我開始執行隊列中的第一個函數

這樣做的好處在於函數數組是線性展開,增減起來非常方便。而且,當不要要繼續進行接下來動畫的時候(比如使用者點了某個按鈕),只需要清空那個隊列即可。而要增加更多則只需要排入佇列即可。

//清空隊列$(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);

JQuery隊列queue與原生模仿其實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.