手風琴是側邊欄導航、FAQ、內容摺疊的經典 UI 模式。本文提供一個**完整、可擴展、無外部依賴 (僅需 jQuery)** 的手風琴插件實現,包含:語義化 HTML 結構、BEM 風格 CSS、支援 JSON 配置動態渲染的 jQuery 插件封裝、鍵盤無障礙支援、多實例隔離。
<ul id="accordion" class="accordion" role="tablist">
<!-- 由 JS 動態渲染,此處為容器 -->
</ul>
/* === 變量與重置 === */
.accordion {
--bg-color: #f2f2f2;
--hover-bg: #4a5b79;
--text-color: #333;
--active-text: #fff;
--border-color: #000;
padding: 0;
list-style: none;
width: 100%;
max-width: 300px;
}
/* === 一級項目 === */
.accordion > li {
border-top: 1px solid var(--border-color);
}
.accordion > li:first-child { border-top: none; }
/* 標題觸發區 */
.titlemenu {
display: flex;
align-items: center;
height: 40px;
padding: 0 16px;
background: var(--bg-color);
cursor: pointer;
user-select: none;
transition: background 0.2s;
}
.titlemenu:hover { background: #e6e6e6; }
.titlemenu[aria-expanded="true"] { background: var(--hover-bg); color: var(--active-text); }
.titlemenu img { width: 16px; height: 16px; margin-right: 12px; flex-shrink: 0; }
.titlemenu span { flex: 1; font-weight: 500; }
.titlemenu::after {
content: '▼';
font-size: 10px;
transition: transform 0.2s;
color: #666;
}
.titlemenu[aria-expanded="true"]::after { transform: rotate(-180deg); }
/* 子選單 */
.submenu {
display: none; /* JS 控制 slideDown/Up */
padding: 0;
list-style: none;
background: #fff;
}
.submenu > li { border-top: 1px solid #eee; }
.submenu > li:first-child { border-top: none; }
.submenu a {
display: flex;
align-items: center;
height: 36px;
padding: 0 16px 0 40px;
color: #333;
text-decoration: none;
transition: background 0.15s, color 0.15s;
}
.submenu a:hover {
background: var(--hover-bg);
color: var(--active-text);
}
.submenu img { width: 16px; height: 16px; margin-right: 12px; }
/* 懸停高亮類 (JS 切換) */
.submenu li.hover a {
background: var(--hover-bg);
color: var(--active-text);
}
(function($) {
'use strict';
// 默認配置
var defaults = {
data: [], // [{ title, icon, submenu: [{ title, icon, href, id }] }]
singleOpen: true, // 手風琴模式:同層只展開一個
animateSpeed: 300,
onItemClick: null, // 回調: function(itemData, $li, instance)
onToggle: null // 回調: function(isOpen, $li, instance)
};
// 構造函式
function Accordion($container, options) {
this.$container = $container;
this.options = $.extend(true, {}, defaults, options);
this._init();
}
Accordion.prototype._init = function() {
var self = this;
var opts = this.options;
var html = '';
// 1. 根據 data 渲染 HTML
opts.data.forEach(function(item, index) {
html += '';
html += '';
if (item.submenu && item.submenu.length) {
html += '';
}
html += ' ';
});
this.$container.html(html).addClass('accordion');
this.$items = this.$container.children('li');
this.$titles = this.$container.find('.titlemenu');
this.$submenus = this.$container.find('.submenu');
// 2. 綁定事件
this._bindEvents();
};
Accordion.prototype._bindEvents = function() {
var self = this;
var opts = this.options;
// 點擊標題切換
this.$titles.on('click.accordion keypress.accordion', function(e) {
if (e.type === 'keypress' && e.key !== 'Enter' && e.key !== ' ') return;
e.preventDefault();
var $title = $(this);
var $li = $title.parent();
var index = $li.index();
self.toggle(index);
});
// 子選單項懸停高亮 (純 CSS :hover 已覆蓋,此處保留 JS 方案兼容舊瀏覽器)
this.$container.on('mouseenter.accordion', '.submenu li', function() {
$(this).addClass('hover').siblings().removeClass('hover');
}).on('mouseleave.accordion', '.submenu', function() {
$(this).find('li.hover').removeClass('hover');
});
// 子選單點擊事件
this.$container.on('click.accordion', '.submenu a', function(e) {
var $a = $(this);
var itemData = {
id: $a.data('id'),
title: $a.find('span').text(),
href: $a.attr('href')
};
if (opts.onItemClick) {
opts.onItemClick.call(self, itemData, $a.parent(), self);
}
});
};
// 公開方法:切換指定索引
Accordion.prototype.toggle = function(index) {
var $li = this.$items.eq(index);
var $title = $li.children('.titlemenu');
var $submenu = $li.children('.submenu');
var isOpen = $title.attr('aria-expanded') === 'true';
var opts = this.options;
// 手風琴模式:關閉其他
if (opts.singleOpen && !isOpen) {
this.$titles.filter('[aria-expanded="true"]').each(function() {
var $otherTitle = $(this);
var $otherLi = $otherTitle.parent();
var otherIndex = $otherLi.index();
if (otherIndex !== index) self.close(otherIndex);
});
}
if (isOpen) {
this.close(index);
} else {
this.open(index);
}
};
Accordion.prototype.open = function(index) {
var $li = this.$items.eq(index);
var $title = $li.children('.titlemenu');
var $submenu = $li.children('.submenu');
if (!$submenu.length) return; // 無子選單
$title.attr('aria-expanded', 'true');
$submenu.slideDown(this.options.animateSpeed);
this.options.onToggle && this.options.onToggle(true, $li, this);
};
Accordion.prototype.close = function(index) {
var $li = this.$items.eq(index);
var $title = $li.children('.titlemenu');
var $submenu = $li.children('.submenu');
$title.attr('aria-expanded', 'false');
$submenu.slideUp(this.options.animateSpeed);
this.options.onToggle && this.options.onToggle(false, $li, this);
};
Accordion.prototype.destroy = function() {
this.$container.off('.accordion').empty().removeClass('accordion');
this.$container.data('accordion', null);
};
// jQuery 插件入口
$.fn.accordion = function(options) {
return this.each(function() {
var $this = $(this);
var instance = $this.data('accordion');
if (!instance) {
instance = new Accordion($this, options);
$this.data('accordion', instance);
} else if (options) {
// 更新選項 (簡易合併)
$.extend(true, instance.options, options);
}
});
};
// 暴露構造函式供進階用法
$.fn.accordion.Constructor = Accordion;
})(jQuery);
$(function() {
var menuData = [
{
title: '一級目錄',
icon: 'images/cog.png',
submenu: [
{ title: '二級目錄 1', icon: 'images/monitor.png', href: '#', id: '1' },
{ title: '二級目錄 2', icon: 'images/monitor.png', href: '#', id: '2' },
{ title: '二級目錄 3', icon: 'images/monitor.png', href: '#', id: '3' }
]
},
{
title: '一級目錄',
icon: 'images/cog.png',
submenu: [
{ title: '二級目錄 4', icon: 'images/monitor.png', href: '#', id: '4' },
{ title: '二級目錄 5', icon: 'images/monitor.png', href: '#', id: '5' }
]
}
];
$('#accordion').accordion({
data: menuData,
singleOpen: true,
animateSpeed: 300,
onItemClick: function(item, $li) {
console.log('點擊子項:', item);
// 可在此處理路由跳轉、AJAX 載入等
},
onToggle: function(isOpen, $li) {
console.log(isOpen ? '展開' : '摺疊', $li.find('.titlemenu span').text());
}
});
});
| 特性 | 實現方式 |
|---|---|
| 數據驅動渲染 | JSON 配置 → HTML 字串模板 → .html(),支援動態更新 |
| 無障礙 (a11y) | ARIA 屬性 (role, aria-expanded, aria-controls)、鍵盤 Enter/Space 觸發、tabindex |
| 多實例隔離 | 每個容器獨立實例,.data('accordion') 存儲,互不干擾 |
| 事件命名空間 | .on('click.accordion'),destroy() 可精確卸載 |
| 動畫控制 | slideDown/Up + 可配置速度,CSS transition 兜底 |
| 圖標容錯 | 缺失 icon 時使用 1px 透明 base64 gif 佔位,不破壞佈局 |
submenu 為函式,open 時首次載入並緩存submenu 內再含 submenu,CSS 增加層級縮進localStorage 記錄展開索引,初始化時恢復.stop(true, true) 防止排隊這個手風琴插件展示了 **「配置化數據 + 模板渲染 + 事件委派 + ARIA 無障礙 + 實例化管理」** 的現代 jQuery 組件開發範式。雖然 Vue/React 時代組件化更優雅,但在維護 jQuery 專案、快速原型、無建構工具環境下,這套代碼結構清晰、擴展性強、可直接投入生產使用。