萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 手風琴導航菜單:動畫展開收合與狀態管理

效果預覽

經典的垂直手風琴導航:

  • 點擊主選單項目,展開/收合子選單
  • 同層互斥:展開一個自動收合其他
  • 平滑高度動畫(animate({height: 'show/hide'}))
  • 防止動畫佇列堆疊(:animated 判斷)

HTML 結構

<div class="menu_list" id="accordion">
  <ul>
    <li>
      <a href="javascript:void(0);" class="trigger">網頁特效</a>
      <div class="submenu">JS特效、CSS3動畫、Canvas繪圖</div>
    </li>
    <li>
      <a href="javascript:void(0);" class="trigger">網頁模板</a>
      <div class="submenu">企業官網、電商模板、後台模板</div>
    </li>
    <li>
      <a href="javascript:void(0);" class="trigger">聯系我們</a>
      <div class="submenu">關於我們、加入我們、聯系方式</div>
    </li>
  </ul>
</div>

CSS 樣式

.menu_list { width: 260px; border: 1px solid #ddd; border-radius: 4px; overflow: hidden; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
.menu_list > ul > li { border-bottom: 1px solid #eee; }
.menu_list > ul > li:last-child { border-bottom: none; }
.trigger {
  display: block; padding: 14px 20px;
  background: #f8f9fa; color: #2c3e50; text-decoration: none;
  font-weight: 500; border: none; width: 100%; text-align: left;
  cursor: pointer; transition: background 0.2s;
}
.trigger:hover, .trigger:focus { background: #e9ecef; outline: none; }
.trigger::after {
  content: "+"; float: right; font-size: 1.2em; line-height: 1;
  transition: transform 0.3s; color: #7f8c8d;
}
.trigger[aria-expanded="true"]::after { transform: rotate(45deg); } /* + 變 × */
.submenu {
  display: none; padding: 12px 20px; background: #fff;
  color: #555; font-size: 0.9em; line-height: 1.6; border-top: 1px solid #eee;
}

jQuery 實作(原始版本優化)

(function($) {
  $.fn.accordion = function(options) {
    const settings = $.extend({
      trigger: ".trigger",
      panel: ".submenu",
      speed: 300,
      easing: "swing",
      singleOpen: true,     // 互斥模式
      headerClass: "active" // 觸發器激活類別
    }, options);
    
    return this.each(function() {
      const $container = $(this);
      const $triggers = $container.find(settings.trigger);
      
      $triggers.on("click.accordion", function(e) {
        e.preventDefault();
        const $trigger = $(this);
        const $panel = $trigger.next(settings.panel);
        const isOpen = $trigger.hasClass(settings.headerClass);
        
        // 動畫中忽略點擊
        if ($panel.is(":animated")) return;
        
        if (settings.singleOpen) {
          // 關閉其他已開啟的面板
          $triggers.not($trigger).filter("." + settings.headerClass).each(function() {
            const $otherTrigger = $(this);
            const $otherPanel = $otherTrigger.next(settings.panel);
            if (!$otherPanel.is(":animated")) {
              $otherTrigger.removeClass(settings.headerClass)
                .attr("aria-expanded", "false");
              $otherPanel.slideUp(settings.speed, settings.easing);
            }
          });
        }
        
        // 切換當前面板
        if (isOpen) {
          $trigger.removeClass(settings.headerClass).attr("aria-expanded", "false");
          $panel.slideUp(settings.speed, settings.easing);
        } else {
          $trigger.addClass(settings.headerClass).attr("aria-expanded", "true");
          $panel.slideDown(settings.speed, settings.easing);
        }
      });
      
      // 鍵盤支援
      $triggers.on("keydown.accordion", function(e) {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          $(this).click();
        }
        // 方向鍵導航
        if (e.key === "ArrowDown") {
          e.preventDefault();
          $(this).closest("li").next().find(settings.trigger).first().focus();
        }
        if (e.key === "ArrowUp") {
          e.preventDefault();
          $(this).closest("li").prev().find(settings.trigger).first().focus();
        }
      });
    });
  };
})(jQuery);

// 初始化
$(function() {
  $("#accordion").accordion({
    speed: 250,
    easing: "easeOutCubic"
  });
});

原生 JavaScript 重構(無依賴、更輕量)

class Accordion {
  constructor(container, options = {}) {
    this.container = typeof container === "string" 
      ? document.querySelector(container) : container;
    if (!this.container) return;
    
    this.options = Object.assign({
      triggerSelector: ".trigger",
      panelSelector: ".submenu",
      duration: 300,
      singleOpen: true,
      activeClass: "active"
    }, options);
    
    this.triggers = Array.from(this.container.querySelectorAll(this.options.triggerSelector));
    this.init();
  }
  
  init() {
    this.triggers.forEach(trigger => {
      trigger.addEventListener("click", (e) => this.toggle(trigger));
      trigger.addEventListener("keydown", (e) => this.handleKeydown(trigger, e));
      // 初始化 ARIA
      const panel = trigger.nextElementSibling;
      trigger.setAttribute("aria-expanded", "false");
      trigger.setAttribute("aria-controls", panel.id || `panel-${Math.random().toString(36).substr(2,9)}`);
      if (!panel.id) panel.id = trigger.getAttribute("aria-controls");
    });
  }
  
  toggle(trigger) {
    const panel = trigger.nextElementSibling;
    const isOpen = trigger.classList.contains(this.options.activeClass);
    
    // 動畫中忽略
    if (panel.dataset.animating === "true") return;
    
    if (this.options.singleOpen) {
      this.triggers.forEach(other => {
        if (other !== trigger && other.classList.contains(this.options.activeClass)) {
          this.close(other);
        }
      });
    }
    
    isOpen ? this.close(trigger) : this.open(trigger);
  }
  
  open(trigger) {
    const panel = trigger.nextElementSibling;
    panel.dataset.animating = "true";
    panel.style.display = "block";
    const height = panel.scrollHeight + "px";
    panel.style.height = "0";
    panel.offsetHeight; // 強制回流
    panel.style.transition = `height ${this.options.duration}ms ease`;
    panel.style.height = height;
    
    trigger.classList.add(this.options.activeClass);
    trigger.setAttribute("aria-expanded", "true");
    
    setTimeout(() => {
      panel.style.height = "";
      panel.style.transition = "";
      panel.dataset.animating = "false";
    }, this.options.duration);
  }
  
  close(trigger) {
    const panel = trigger.nextElementSibling;
    panel.dataset.animating = "true";
    panel.style.height = panel.scrollHeight + "px";
    panel.offsetHeight;
    panel.style.transition = `height ${this.options.duration}ms ease`;
    panel.style.height = "0";
    
    trigger.classList.remove(this.options.activeClass);
    trigger.setAttribute("aria-expanded", "false");
    
    setTimeout(() => {
      panel.style.display = "none";
      panel.style.height = "";
      panel.style.transition = "";
      panel.dataset.animating = "false";
    }, this.options.duration);
  }
  
  handleKeydown(trigger, e) {
    const index = this.triggers.indexOf(trigger);
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault(); this.toggle(trigger);
    } else if (e.key === "ArrowDown" && index < this.triggers.length - 1) {
      e.preventDefault(); this.triggers[index + 1].focus();
    } else if (e.key === "ArrowUp" && index > 0) {
      e.preventDefault(); this.triggers[index - 1].focus();
    } else if (e.key === "Home") {
      e.preventDefault(); this.triggers[0].focus();
    } else if (e.key === "End") {
      e.preventDefault(); this.triggers[this.triggers.length - 1].focus();
    }
  }
}

// 使用
document.addEventListener("DOMContentLoaded", () => {
  new Accordion("#accordion", { duration: 250 });
});

進階功能擴充

功能實作要點
巢狀手風琴子選單內再嵌套 .trigger/.submenu,CSS 增加縮進 padding-left: 20px,JS 避免事件衝突 e.stopPropagation()
URL 錨點定位頁面載入時檢查 location.hash,自動展開對應面板並滾動至視野
狀態持久化使用 localStorage 記錄展開項目 ID,刷新頁面恢復狀態
動態載入內容面板內容為空時,展開瞬間發起 AJAX 載入,顯示骨架屏
響應式斷點行動裝置改為全展開或底部抽屜模式,使用 matchMedia 監聽

常見問題排查

現象原因解決
動畫卡頓、跳動height: auto 無法動畫、內容有 margin collapse使用 scrollHeight 獲取確切高度、子元素改用 padding 而非 margin
快速連點導致面板狀態錯亂未檢查 :animated / dataset.animating添加動畫狀態鎖、或使用 .stop(true, true) (jQuery)
內容動態變更後高度錯誤動畫結束時高度已固定動畫結束後設定 height: auto、或使用 CSS Grid grid-template-rows: 0fr 1fr 技巧

總結

手風琴導航是資訊架構中「漸進揭露」的經典模式。從 jQuery slideToggle 到原生 CSS transition + scrollHeight,核心邏輯不變:狀態機 + 動畫協調 + 無障礙屬性同步。現代開發建議採用原生實現(無依賴、效能優、體積小),搭配 CSS @media (prefers-reduced-motion) 尊重用戶動畫偏好。

copyright © 萬盛學電腦網 all rights reserved