"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/jquery-plugin-accordion-lab/explore-plugin-accordion.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-plugin-accordion.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a898.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip