"""Offline Playwright Chromium lab for jQuery UI Ch 24: Button."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Button Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; }
.ui-button { display: inline-block; padding: 4px 10px; border: 1px solid #999; background: #eee; cursor: pointer; }
.ui-state-active { background: #007bff; color: #fff; }
.ui-button-icon-only .ui-button-text { display: none; }
.ui-menu { position: absolute; width: 110px; list-style: none; margin: 0; padding: 4px; border: 1px solid #666; background: #fff; }
.hidden { display: none; }
input[type=checkbox].ui-helper-hidden-accessible,
input[type=radio].ui-helper-hidden-accessible { position: absolute; left: -9999px; }
</style>
</head>
<body>
<div id="basic-group">
<button id="btn-el">一个 button 元素</button>
<input id="submit-el" type="submit" value="一个提交按钮">
<a id="anchor-el" href="#nav">一个锚</a>
</div>
<div id="icon-group">
<button id="ic1">只带有图标的按钮</button>
<button id="ic2">图标在左侧的按钮</button>
<button id="ic3">带有两个图标的按钮</button>
<button id="ic4">带有两个图标且不带文本的按钮</button>
</div>
<input type="checkbox" id="check"><label for="check" id="lbl-check">切换</label>
<div id="format">
<input type="checkbox" id="c1"><label for="c1" id="lbl-c1">B</label>
<input type="checkbox" id="c2"><label for="c2" id="lbl-c2">I</label>
<input type="checkbox" id="c3"><label for="c3" id="lbl-c3">U</label>
</div>
<div id="radio">
<input type="radio" id="r1" name="radio"><label for="r1" id="lbl-r1">选择 1</label>
<input type="radio" id="r2" name="radio" checked><label for="r2" id="lbl-r2">选择 2</label>
<input type="radio" id="r3" name="radio"><label for="r3" id="lbl-r3">选择 3</label>
</div>
<div id="split-wrap">
<div id="split-set">
<button id="rerun">运行最后的动作</button>
<button id="select-action">选择一个动作</button>
</div>
<ul id="split-menu" class="ui-menu hidden">
<li><a href="#">打开...</a></li>
<li><a href="#">保存</a></li>
<li><a href="#">删除</a></li>
</ul>
</div>
<div id="toolbar">
<button id="play" data-label="play" data-icon="ui-icon-play">play</button>
<button id="stop">stop</button>
<input type="checkbox" id="shuffle"><label for="shuffle" id="lbl-shuffle">Shuffle</label>
<span id="repeat">
<input type="radio" id="repeat0" name="repeat" checked><label for="repeat0" id="lbl-rep0">No Repeat</label>
<input type="radio" id="repeat1" name="repeat"><label for="repeat1" id="lbl-rep1">Once</label>
<input type="radio" id="repeatall" name="repeat"><label for="repeatall" id="lbl-repall">All</label>
</span>
</div>
<script>
window.clickState = { basicPrevented: 0, rerunCount: 0 };
["btn-el", "submit-el", "anchor-el"].forEach(id => {
const el = document.getElementById(id);
el.classList.add("ui-button");
el.addEventListener("click", e => {
e.preventDefault();
window.clickState.basicPrevented += 1;
});
});
function applyIconButton(id, primary, secondary, showText) {
const el = document.getElementById(id);
const label = el.textContent;
el.classList.add("ui-button");
if (!showText) el.classList.add("ui-button-icon-only");
el.dataset.primary = primary || "";
el.dataset.secondary = secondary || "";
el.dataset.text = String(showText);
el.innerHTML = (primary ? `<span class="ui-icon ${primary}"></span>` : "") +
`<span class="ui-button-text">${label}</span>` +
(secondary ? `<span class="ui-icon ${secondary}"></span>` : "");
}
applyIconButton("ic1", "ui-icon-locked", null, false);
applyIconButton("ic2", "ui-icon-locked", null, true);
applyIconButton("ic3", "ui-icon-gear", "ui-icon-triangle-1-s", true);
applyIconButton("ic4", "ui-icon-gear", "ui-icon-triangle-1-s", false);
function bindCheckButton(inputId, labelId) {
const inp = document.getElementById(inputId);
const lbl = document.getElementById(labelId);
inp.classList.add("ui-helper-hidden-accessible");
lbl.classList.add("ui-button");
const sync = () => lbl.classList.toggle("ui-state-active", inp.checked);
inp.addEventListener("change", sync);
sync();
}
bindCheckButton("check", "lbl-check");
bindCheckButton("c1", "lbl-c1");
bindCheckButton("c2", "lbl-c2");
bindCheckButton("c3", "lbl-c3");
bindCheckButton("shuffle", "lbl-shuffle");
function bindRadioSet(name) {
const radios = Array.from(document.querySelectorAll(`input[name="${name}"]`));
const syncAll = () => {
radios.forEach(r => {
const lbl = document.querySelector(`label[for="${r.id}"]`);
lbl.classList.add("ui-button");
lbl.classList.toggle("ui-state-active", r.checked);
});
};
radios.forEach(r => {
r.classList.add("ui-helper-hidden-accessible");
r.addEventListener("change", syncAll);
});
syncAll();
}
bindRadioSet("radio");
bindRadioSet("repeat");
const splitMenu = document.getElementById("split-menu");
document.getElementById("rerun").addEventListener("click", () => { window.clickState.rerunCount += 1; });
document.getElementById("select-action").addEventListener("click", e => {
e.stopPropagation();
splitMenu.classList.remove("hidden");
const closeOnce = () => { splitMenu.classList.add("hidden"); document.removeEventListener("click", closeOnce); };
document.addEventListener("click", closeOnce);
});
const playBtn = document.getElementById("play");
playBtn.addEventListener("click", () => {
if (playBtn.dataset.label === "play") {
playBtn.dataset.label = "pause";
playBtn.dataset.icon = "ui-icon-pause";
playBtn.textContent = "pause";
} else {
playBtn.dataset.label = "play";
playBtn.dataset.icon = "ui-icon-play";
playBtn.textContent = "play";
}
});
document.getElementById("stop").addEventListener("click", () => {
playBtn.dataset.label = "play";
playBtn.dataset.icon = "ui-icon-play";
playBtn.textContent = "play";
});
</script>
</body>
</html>
"""
def main():
cases = []
with sync_playwright() as p:
try:
browser = p.chromium.launch(headless=True)
except Exception:
browser = p.chromium.launch(headless=True, channel="chrome")
page = browser.new_page()
page.set_content(HTML_DOC)
# Case 1: Default button types + 4 icon button configurations
page.click("#btn-el")
page.click("#submit-el")
page.click("#anchor-el")
res1 = page.evaluate("""() => ({
basicPrevented: window.clickState.basicPrevented,
allStyled: ["btn-el", "submit-el", "anchor-el"].every(id => document.getElementById(id).classList.contains("ui-button")),
icons: ["ic1", "ic2", "ic3", "ic4"].map(id => {
const el = document.getElementById(id);
return {
primary: el.dataset.primary,
secondary: el.dataset.secondary,
textShown: el.dataset.text === "true"
};
})
})""")
exp1 = {
"basicPrevented": 3,
"allStyled": True,
"icons": [
{"primary": "ui-icon-locked", "secondary": "", "textShown": False},
{"primary": "ui-icon-locked", "secondary": "", "textShown": True},
{"primary": "ui-icon-gear", "secondary": "ui-icon-triangle-1-s", "textShown": True},
{"primary": "ui-icon-gear", "secondary": "ui-icon-triangle-1-s", "textShown": False},
],
}
cases.append(dict(name="button_default_and_icons", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Checkbox button & buttonset + radio buttonset
page.click("#lbl-check")
page.click("#lbl-c1")
page.click("#lbl-c3")
radio_before = page.evaluate("""() => Array.from(document.querySelectorAll('#radio label')).map(l => l.classList.contains('ui-state-active'))""")
page.click("#lbl-r3")
res2 = page.evaluate("""(radioBefore) => ({
checkActive: document.getElementById("lbl-check").classList.contains("ui-state-active"),
formatStates: ["lbl-c1", "lbl-c2", "lbl-c3"].map(id => document.getElementById(id).classList.contains("ui-state-active")),
radioBefore,
radioAfter: Array.from(document.querySelectorAll('#radio label')).map(l => l.classList.contains('ui-state-active'))
})""", radio_before)
exp2 = {
"checkActive": True,
"formatStates": [True, False, True],
"radioBefore": [False, True, False],
"radioAfter": [False, False, True],
}
cases.append(dict(name="button_checkbox_and_radio_buttonset", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Split button rerun + dropdown menu open & document click close
page.click("#rerun")
page.click("#select-action")
menu_open = page.evaluate("""() => !document.getElementById("split-menu").classList.contains("hidden")""")
menu_items = page.evaluate("""() => Array.from(document.querySelectorAll("#split-menu li a")).map(a => a.textContent)""")
page.click("body", position={"x": 5, "y": 5})
menu_closed = page.evaluate("""() => document.getElementById("split-menu").classList.contains("hidden")""")
res3 = {
"rerunCount": page.evaluate("() => window.clickState.rerunCount"),
"menuOpen": menu_open,
"menuItems": menu_items,
"menuClosedAfterDocClick": menu_closed,
}
exp3 = {
"rerunCount": 1,
"menuOpen": True,
"menuItems": ["打开...", "保存", "删除"],
"menuClosedAfterDocClick": True,
}
cases.append(dict(name="button_splitbutton_menu", expected=exp3, actual=res3, passed=(res3 == exp3)))
# Case 4: Media toolbar play/pause/stop + shuffle checkbox + repeat radio set
page.click("#play")
playing_state = page.evaluate("""() => ({ label: play.dataset.label, icon: play.dataset.icon })""")
page.click("#stop")
stopped_state = page.evaluate("""() => ({ label: play.dataset.label, icon: play.dataset.icon })""")
page.click("#lbl-shuffle")
page.click("#lbl-repall")
res4 = page.evaluate("""([playing, stopped]) => ({
playing,
stopped,
shuffleChecked: document.getElementById("shuffle").checked,
repeatSelected: document.querySelector('input[name="repeat"]:checked').id
})""", [playing_state, stopped_state])
exp4 = {
"playing": {"label": "pause", "icon": "ui-icon-pause"},
"stopped": {"label": "play", "icon": "ui-icon-play"},
"shuffleChecked": True,
"repeatSelected": "repeatall",
}
cases.append(dict(name="button_media_toolbar", expected=exp4, actual=res4, passed=(res4 == exp4)))
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/jqueryui-example-button-lab/explore-example-button.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-example-button.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a923.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip