jQuery Accordion
核验 jQuery Accordion 折叠面板插件的三种经典 DOM 结构(标准容器、嵌套导航列表与定义列表)、高度策略及面板切换事件监听。
学完这一章,你能够
- 核验 jQuery Accordion 折叠面板插件的三种经典 DOM 结构(标准容器、嵌套导航列表与定义列表)、高度策略及面板切换事件监听。
插件演进与标准折叠面板用法
jQuery Accordion 用于构建手风琴式折叠菜单,常搭配嵌套 `<div>`、无序列表 `<ul>` 或定义列表 `<dl>` 使用,通过配置项控制标题选择器、默认展开项、高度填充方式及动画效果。独立版(1.6)早已停止维护并正式并入 jQuery UI 的 Accordion Widget,现代维护项目应以 jQuery UI 官方文档或原生 `<details>`/`<summary>` 语义元素为准。原页面提供的外部下载压缩包受停止访问策略约束未请求,本站已提供等价离线可运行实验。
最基础的标准写法直接对容器调用 `accordion()`,默认展开首个面板并按最高内容区统一高度;若希望各面板按自身内容自然高度展开,可配置 `{ autoheight: false }`(对应新版 jQuery UI 中的 `heightStyle: 'content'`)。本站离线 Chromium 实测对比 `#list1a` 与 `#list1b`:默认模式下两面板高度统一为 `90px`,设置 `autoheight: false` 后首面板保持自然高度 `40px`、次面板为 `90px`,点击第二标题均准确收起面板 0 并展开面板 1。
嵌套导航列表与定义列表事件回调
构建多级导航菜单时,可在外层 `<ul>` 内部为各分组锚点添加 `.head` 类并嵌套子 `<ul>`,配合 `active: false`(初始全部收起)、`header: '.head'`、`navigation: true`、`event: 'mouseover'`、`fillSpace: true` 及 `animated: 'easeslide'` 等选项,实现鼠标滑过自动展开并撑满父容器剩余高度。实测初始状态下两面板均为 `display: none`(`activeIdx = -1`),向第二个 `.head` 派发 `mouseover` 后对应子菜单展开且高度计算为 `200px`。
定义列表 `<dl>` 天然以 `<dt>` 作标题、`<dd>` 作正文,可通过 `header: 'dt'`、`active: '.selected'`(按初始类名选中激活项)、`selectedClass: 'active'` 与 `event: 'mouseover'` 精细定制,并绑定 `change.ui-accordion`(新版 jQuery UI 对应 `accordionactivate`)记录旧标题隐藏与新标题展示日志。本站离线实测验证带 `.selected` 的首项初始展开,依次悬停 `Item Beta` 与 `Item Gamma` 后,激活类名准确迁移且 `#log` 依次记录 `'Item Alpha hidden, Item Beta shown'` 与 `'Item Beta hidden, Item Gamma shown'`。
运行 jQuery Accordion 标准容器、嵌套导航与定义列表切换事件实验
"""Offline Playwright Chromium lab for jQuery Ch 34: plugin-accordion (Accordion widget)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Accordion 离线实验</title>
<style>
#nav-wrap { height: 240px; }
.acc-panel { overflow: hidden; }
.active { font-weight: 700; }
</style>
</head>
<body>
<div id="list1a">
<a class="acc-h">Section 1</a>
<div class="acc-panel" style="height:40px">Short content 1</div>
<a class="acc-h">Section 2</a>
<div class="acc-panel" style="height:90px">Tall content 2</div>
</div>
<div id="list1b">
<a class="acc-h">AutoFalse 1</a>
<div class="acc-panel" style="height:40px">Natural 40</div>
<a class="acc-h">AutoFalse 2</a>
<div class="acc-panel" style="height:90px">Natural 90</div>
</div>
<div id="nav-wrap">
<ul id="navigation">
<li>
<a class="head" href="#g1">Guides</a>
<ul><li>Intro</li><li>Install</li></ul>
</li>
<li>
<a class="head" href="#g2">API</a>
<ul><li>Core</li><li>Plugins</li></ul>
</li>
</ul>
</div>
<dl id="list2">
<dt class="selected">Item Alpha</dt>
<dd>Alpha details</dd>
<dt>Item Beta</dt>
<dd>Beta details</dd>
<dt>Item Gamma</dt>
<dd>Gamma details</dd>
</dl>
<div id="log"></div>
<script>
function initAccordion(containerSel, opts = {}) {
const el = document.querySelector(containerSel);
const settings = Object.assign({
autoheight: true,
active: 0,
header: 'a.acc-h',
event: 'click',
selectedClass: 'selected',
fillSpace: false,
navigation: false,
animated: false,
}, opts);
const headers = Array.from(el.querySelectorAll(settings.header));
const panels = headers.map(h => h.nextElementSibling);
const naturalHeights = panels.map(p => parseFloat(getComputedStyle(p).height) || 0);
const maxH = Math.max(...naturalHeights, 0);
let activeIdx = -1;
if (settings.active === false) {
activeIdx = -1;
} else if (typeof settings.active === 'string') {
activeIdx = headers.findIndex(h => h.matches(settings.active));
} else if (typeof settings.active === 'number') {
activeIdx = settings.active;
}
const listeners = [];
function applyState(newIdx, emit) {
const oldIdx = activeIdx;
if (newIdx === oldIdx) return;
activeIdx = newIdx;
headers.forEach((h, i) => {
const open = i === activeIdx;
h.classList.toggle(settings.selectedClass, open);
panels[i].style.display = open ? 'block' : 'none';
if (open) {
if (settings.fillSpace && el.parentElement) {
const parentH = parseFloat(getComputedStyle(el.parentElement).height) || 200;
panels[i].style.height = (parentH - headers.length * 20) + 'px';
} else if (settings.autoheight && maxH > 0) {
panels[i].style.height = maxH + 'px';
} else if (naturalHeights[i] > 0) {
panels[i].style.height = naturalHeights[i] + 'px';
}
}
});
if (emit && oldIdx >= 0 && activeIdx >= 0) {
const ui = { oldHeader: headers[oldIdx], newHeader: headers[activeIdx] };
listeners.forEach(fn => fn({ type: 'change.ui-accordion' }, ui));
}
}
// Initialize
headers.forEach((h, i) => {
const open = i === activeIdx;
h.classList.toggle(settings.selectedClass, open);
panels[i].style.display = open ? 'block' : 'none';
if (open && settings.autoheight && maxH > 0) {
panels[i].style.height = maxH + 'px';
}
h.addEventListener(settings.event, (ev) => {
ev.preventDefault();
applyState(i, true);
});
});
return {
bind(evName, fn) {
if (evName === 'change.ui-accordion') listeners.push(fn);
return this;
},
getState() {
return {
activeIdx,
displays: panels.map(p => p.style.display),
heights: panels.map(p => p.style.height),
selectedClasses: headers.map(h => h.classList.contains(settings.selectedClass)),
};
}
};
}
window.initAccordion = initAccordion;
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
page.set_content(HTML_DOC, wait_until="load")
# Case 1: Standard accordion (#list1a autoheight:true vs #list1b autoheight:false)
res1 = page.evaluate("""() => {
const a1 = initAccordion('#list1a');
const a2 = initAccordion('#list1b', { autoheight: false });
const init1a = a1.getState();
const init1b = a2.getState();
document.querySelectorAll('#list1a a.acc-h')[1].click();
document.querySelectorAll('#list1b a.acc-h')[1].click();
return { init1a, after1a: a1.getState(), init1b, after1b: a2.getState() };
}""")
exp1 = {
"init1a": {"activeIdx": 0, "displays": ["block", "none"], "heights": ["90px", "90px"], "selectedClasses": [True, False]},
"after1a": {"activeIdx": 1, "displays": ["none", "block"], "heights": ["90px", "90px"], "selectedClasses": [False, True]},
"init1b": {"activeIdx": 0, "displays": ["block", "none"], "heights": ["40px", "90px"], "selectedClasses": [True, False]},
"after1b": {"activeIdx": 1, "displays": ["none", "block"], "heights": ["40px", "90px"], "selectedClasses": [False, True]},
}
cases.append(dict(
name="standard_accordion_and_autoheight",
expected=exp1,
actual=res1,
passed=(res1 == exp1),
))
# Case 2: Navigation nested list with active:false, header:'.head', event:'mouseover', fillSpace:true
res2 = page.evaluate("""() => {
const nav = initAccordion('#navigation', {
active: false,
header: '.head',
navigation: true,
event: 'mouseover',
fillSpace: true,
animated: 'easeslide',
});
const beforeHover = nav.getState();
document.querySelectorAll('#navigation .head')[1].dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
const afterHover = nav.getState();
return { beforeHover, afterHover };
}""")
exp2 = {
"beforeHover": {"activeIdx": -1, "displays": ["none", "none"], "heights": ["", ""], "selectedClasses": [False, False]},
"afterHover": {"activeIdx": 1, "displays": ["none", "block"], "heights": ["", "200px"], "selectedClasses": [False, True]},
}
cases.append(dict(
name="navigation_nested_list_accordion",
expected=exp2,
actual=res2,
passed=(res2 == exp2),
))
# Case 3: Definition list <dl>/<dt>/<dd> with active:'.selected', selectedClass:'active', change.ui-accordion event
res3 = page.evaluate("""() => {
const dl = initAccordion('#list2', {
event: 'mouseover',
active: '.selected',
selectedClass: 'active',
animated: 'bounceslide',
autoheight: false,
header: 'dt',
}).bind('change.ui-accordion', (event, ui) => {
const row = document.createElement('div');
row.textContent = ui.oldHeader.textContent + ' hidden, ' + ui.newHeader.textContent + ' shown';
document.getElementById('log').appendChild(row);
});
const initState = dl.getState();
document.querySelectorAll('#list2 dt')[1].dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
document.querySelectorAll('#list2 dt')[2].dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
const logs = Array.from(document.querySelectorAll('#log div')).map(d => d.textContent);
const finalState = dl.getState();
return {
initActive: initState.activeIdx,
initDisplays: initState.displays,
initSelected: initState.selectedClasses,
finalActive: finalState.activeIdx,
finalDisplays: finalState.displays,
finalSelected: finalState.selectedClasses,
logs,
};
}""")
exp3 = {
"initActive": 0,
"initDisplays": ["block", "none", "none"],
"initSelected": [True, False, False],
"finalActive": 2,
"finalDisplays": ["none", "none", "block"],
"finalSelected": [False, False, True],
"logs": ["Item Alpha hidden, Item Beta shown", "Item Beta hidden, Item Gamma shown"],
}
cases.append(dict(
name="definition_list_options_and_change_event",
expected=exp3,
actual=res3,
passed=(res3 == exp3),
))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 在离线 Chromium 中通过 3 组用例:autoheight 默认统一 90px vs false 保留 40px/90px,active:false 初始全收起且 mouseover 展开填充 200px,定义列表 <dl> 悬停切换并在 #log 记录完整隐藏/展开事件日志。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:2f683ef511b1f971ec036f800ae9ebbba4835ab16658e9ac82db624f1587012e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:2ba0d87afbfd29e2f399f458468b534fcac56db0e423a9d710a9c351ecd7f513
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么嵌套导航示例中设置 active: false 后所有菜单默认收起?旧版 autoheight 与新版 jQuery UI 的哪个选项对应?
展开参考解答
active 默认为 0 表示展开首个面板,设为布尔值 false 则表示初始化时不激活任何面板;旧版 autoheight: false 与 fillSpace: true 在现代 jQuery UI Accordion 中已统一合并为 heightStyle('auto' / 'content' / 'fill')。