首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

jQuery Queue/Dequeue 動畫隊列控制完整教學:從回調地獄到線性流程

     編輯:Java 相關知識

jQuery .queue() / .dequeue() 讓多元素、多步驟動畫/異步操作**脫離巢狀回調**,以**線性陣列**聲明流程,極大提升可讀性與可維護性。

核心機制

  • $(el).queue(name, fnArray):將函數陣列推入指定隊列 (預設 "fx" 動畫隊列)。
  • $(el).dequeue(name):取出並執行隊列**首個**函數,**函數內部必須呼叫 dequeue 觸發下一步** (或回傳 Promise/動畫自動觸發)。
  • 隊列綁定在**元素**上,可用 $(document) 作為全域隊列載體。

場景:兩個 Div 依序向右移動 5 步

// 1. 定義線性步驟陣列
var steps = [
    function() { $("#block1").animate({left: "+=100"}, 500, next); },
    function() { $("#block2").animate({left: "+=100"}, 500, next); },
    function() { $("#block1").animate({left: "+=100"}, 500, next); },
    function() { $("#block2").animate({left: "+=100"}, 500, next); },
    function() { $("#block1").animate({left: "+=100"}, 500, next); },
    function() { alert("動畫結束"); }
];

// 2. 統一回調觸發下一步
function next() { $(document).dequeue("myAnim"); }

// 3. 啟動
$(document).queue("myAnim", steps);
next(); // 執行第一步

進階控制

// 清空隊列 (取消剩餘動畫)
$(document).queue("myAnim", []);

// 動態追加步驟
$(document).queue("myAnim", function() { console.log("額外步驟"); $(document).dequeue("myAnim"); });

// 獲取隊列長度
var len = $(document).queue("myAnim").length;

適用場景擴展

  • **AJAX 串聯**:每個請求成功回調呼叫 dequeue,避免 .then().then() 巢狀。
  • **表單分步驗證**:每步驗證通過 dequeue 進入下一步。
  • **遊戲關卡/教學流程**:步驟陣列即腳本,支援動態增刪/暫停/繼續。

原生 JS 替代 (無 jQuery 依賴)

class SimpleQueue {
    constructor() { this.q = []; this.running = false; }
    add(fn) { this.q.push(fn); if (!this.running) this.next(); }
    next() { if (this.q.length === 0) return; this.running = true; this.q.shift()(() => this.next()); }
}
// 用法: const q = new SimpleQueue(); q.add(() => fetch(...).then(q.next)); ...
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved