按钮(Button)
核对 jQuery UI Button 对标准表单元素的主题化增强、图标与文本组合、复选框与单选框 buttonset 按钮组、分割按钮菜单及多媒体播放器工具栏。
学完这一章,你能够
- 核对 jQuery UI Button 对标准表单元素的主题化增强、图标与文本组合、复选框与单选框 buttonset 按钮组、分割按钮菜单及多媒体播放器工具栏。
基础按钮与图标组合
Button 部件为原生 `<button>`、`<input type='submit'>` 和 `<a>` 锚元素赋予统一的悬停(hover)与激活(active)主题样式。初始化时可直接批量选择上述元素调用 `.button()`,并按需调用 `event.preventDefault()` 阻止演示场景下的表单提交或页面跳转(详见官方 Button Widget API)。
通过 `icons: { primary, secondary }` 与布尔选项 `text` 可灵活组合纯图标、左图标带文、双图标带文及双图标无文四种形态。本站离线 Chromium 实测:三类基础元素均挂载 `.ui-button` 且三次点击均被 `preventDefault()` 拦截;4 个图标按钮准确绑定 `ui-icon-locked`、`ui-icon-gear`、`ui-icon-triangle-1-s` 及各自的 `textShown` 状态。
复选框与单选框按钮组(Buttonset)
将 `.button()` 应用于 `<input type='checkbox'>` 时,与之关联的 `<label for='...'>` 会被渲染为可切换状态的按钮;对包含多个复选框或共享 `name` 的多个单选框的公共父容器调用 `.buttonset()`,则可拼合为首尾圆角的连续按钮组(注:jQuery UI 1.12 起推荐使用 `controlgroup` 替代旧版 `buttonset`)。本站实测独立切换复选框及 `B`/`U` 按钮组项可独立激活,而单选按钮组由初始选中第 2 项(`[False, True, False]`)点击第 3 项后互斥切换为 `[False, False, True]`。
分割按钮与下拉菜单
分割按钮(Split Button)把主动作按钮与右侧下拉箭头按钮放进同一 `.buttonset()`,并紧随一个初始隐藏的 `.menu()` 列表:点击主按钮直接执行上次动作,点击下拉箭头则展示菜单并定位至按钮下方,同时在 `document` 上注册一次性点击监听器实现点击空白处自动关闭。本站实测点击主按钮使执行计数增至 `1`,点击下拉按钮展开包含 `['打开...', '保存', '删除']` 的菜单,点击页面空白后菜单自动隐藏。
多媒体播放器工具栏综合实践
播放器工具栏整合了多种 Button 形态:开头/快退/播放/停止/快进/结尾采用无文本纯图标按钮,随机播放(Shuffle)为复选框按钮,循环模式(No Repeat / Once / All)为三项单选按钮组。点击 `#play` 时动态通过 `.button('option', ...)` 在播放与暂停标签及图标间切换,点击 `#stop` 则强制复位为播放状态。本站实测点击 `#play` 切至 `pause`/`ui-icon-pause`,点击 `#stop` 复位为 `play`/`ui-icon-play`,勾选 `#shuffle` 为 `true` 且切换循环模式为 `repeatall`。
在离线 Chromium 中验证 Button 图标组合、复选/单选按钮组、分割按钮与播放器工具栏
"""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()
- 核对三类标准元素按钮化、4 种图标配置、复选框多选与单选互斥状态、分割按钮菜单展开关闭及播放/暂停/停止/Shuffle/Repeat 联动。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:66be8eb72ea8bd2e29ebfb57b41ddb88610548fda775ac71067ed5394ec09c1c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:7384d1cd43f2d4981594552b36d7b56bcbc41018a69d1ed300036bdbdea7c56d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 jQuery UI 中把 checkbox 或 radio 渲染成按钮时,为什么必须配对带有对应 for 属性的 label 元素?
展开参考解答
Button 部件会视觉隐藏原生勾选框/单选圆点,并将关联的 label 元素作为可见按钮表面和文本载体;缺少正确 for 关联将无法正常展示与切换。