jEasyUI 创建分割按钮
通过 easyui-splitbutton 区分主操作按钮区与下拉箭头菜单区,并支持嵌套子菜单的零脚本声明式构建。
学完这一章,你能够
- 通过 easyui-splitbutton 区分主操作按钮区与下拉箭头菜单区,并支持嵌套子菜单的零脚本声明式构建。
分割按钮的双区域交互与声明式构建
分割按钮(Split Button)同样融合了链接按钮与下拉菜单,但将触发区域一分为二:左侧主体像普通按钮一样直接响应点击操作,右侧向下箭头区域则在点击或鼠标悬停时展开关联菜单。标记上只需在工具栏放置 `<a class="easyui-splitbutton" menu="#mm" iconCls="icon-edit">Edit</a>` 及相邻扁平帮助按钮,并定义包含多级 `Open` 子菜单(`Firefox`、`Internet Explorer`、分隔线、`Select Program...`)的 `<div id="mm">`,无需编写 JavaScript 即可完成组件声明。本站离线 Chromium 实测:`Edit` 解析出主操作区(`.s-btn-main`)与箭头区(`.s-btn-downarrow`),点击主区使主操作计数升至 `1` 且菜单保持隐藏;点击箭头区则展开 `#mm` 而不重复触发主操作;在菜单内悬停 `Open` 展开二级子菜单并点击 `Firefox` 后,成功记录 `['Firefox']` 并自动关闭菜单。
离线 Chromium 实测 SplitButton 主区/箭头区分离与多级子菜单选择
展开查看收起
python
"""Offline Playwright Chromium verification lab for jEasyUI SplitButton (Ch13)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jEasyUI SplitButton Lab</title>
<style>
body { margin: 12px; font-family: Arial, sans-serif; }
.toolbar { border: 1px solid #ccc; background: #fafafa; padding: 5px; width: 160px; display: flex; align-items: center; gap: 6px; }
.s-btn-wrap { display: inline-flex; border: 1px solid #bbb; background: #f2f2f2; border-radius: 3px; }
.s-btn-main { padding: 3px 8px; cursor: pointer; font-size: 13px; }
.s-btn-downarrow { padding: 3px 6px; border-left: 1px solid #ccc; cursor: pointer; font-size: 11px; }
.sb-menu { position: absolute; border: 1px solid #95b8e7; background: #fff; display: none; padding: 2px 0; }
.sb-menu .menu-item { padding: 4px 10px; cursor: pointer; position: relative; font-size: 13px; }
.sb-menu .menu-sep { height: 1px; background: #ccc; margin: 3px 0; }
.sb-menu .submenu { position: absolute; left: 100%; top: 0; border: 1px solid #95b8e7; background: #fff; display: none; }
</style>
</head>
<body>
<div class="toolbar">
<a id="sb-edit" href="javascript:void(0)" class="easyui-splitbutton" menu="#mm" iconCls="icon-edit">Edit</a>
<a id="lb-help" href="javascript:void(0)" class="easyui-linkbutton" plain="true" iconCls="icon-help"></a>
</div>
<div id="mm" style="width:150px;">
<div iconCls="icon-undo">Undo</div>
<div iconCls="icon-redo">Redo</div>
<div class="menu-sep"></div>
<div>Cut</div>
<div>Copy</div>
<div>Paste</div>
<div class="menu-sep"></div>
<div id="item-open">
<span>Open</span>
<div id="sub-open" style="width:150px;">
<div>Firefox</div>
<div>Internet Explorer</div>
<div class="menu-sep"></div>
<div>Select Program...</div>
</div>
</div>
<div iconCls="icon-remove">Delete</div>
<div>Select All</div>
</div>
<script>
window.__mainClicks = 0;
window.__menuPicks = [];
const sb = document.getElementById('sb-edit');
const menuEl = document.querySelector(sb.getAttribute('menu'));
menuEl.classList.add('sb-menu');
// Enhance declarative splitbutton into dual zones
const wrap = document.createElement('span');
wrap.className = 's-btn-wrap';
const mainZone = document.createElement('span');
mainZone.className = 's-btn-main';
mainZone.textContent = sb.textContent;
const arrowZone = document.createElement('span');
arrowZone.className = 's-btn-downarrow';
arrowZone.textContent = '▼';
wrap.appendChild(mainZone);
wrap.appendChild(arrowZone);
sb.innerHTML = '';
sb.appendChild(wrap);
mainZone.addEventListener('click', (e) => {
e.stopPropagation();
window.__mainClicks += 1;
});
function showMenu() {
const r = wrap.getBoundingClientRect();
menuEl.style.left = Math.round(r.left) + 'px';
menuEl.style.top = Math.round(r.bottom) + 'px';
menuEl.style.display = 'block';
}
arrowZone.addEventListener('click', (e) => { e.stopPropagation(); showMenu(); });
arrowZone.addEventListener('mouseenter', showMenu);
Array.from(menuEl.children).forEach(ch => {
if (ch.classList.contains('menu-sep')) return;
ch.classList.add('menu-item');
const sub = ch.querySelector(':scope > div');
if (sub) {
sub.classList.add('submenu');
ch.addEventListener('mouseenter', () => { sub.style.display = 'block'; });
ch.addEventListener('mouseleave', () => { sub.style.display = 'none'; });
Array.from(sub.children).forEach(subItem => {
if (!subItem.classList.contains('menu-sep')) {
subItem.classList.add('menu-item');
subItem.addEventListener('click', (e) => {
e.stopPropagation();
window.__menuPicks.push(subItem.textContent.trim());
sub.style.display = 'none';
menuEl.style.display = 'none';
});
}
});
} else {
ch.addEventListener('click', () => {
window.__menuPicks.push(ch.textContent.trim());
menuEl.style.display = 'none';
});
}
});
</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)
page = browser.new_page()
page.set_content(HTML_DOC)
# Case 1: Dual-zone splitbutton structure + adjacent plain linkbutton
act1 = page.evaluate("""() => ({
mainZoneText: document.querySelector('#sb-edit .s-btn-main').textContent.trim(),
hasArrowZone: Boolean(document.querySelector('#sb-edit .s-btn-downarrow')),
menuAttr: document.getElementById('sb-edit').getAttribute('menu'),
helpLinkbuttonPlain: document.getElementById('lb-help').getAttribute('plain') === 'true',
helpLinkbuttonIcon: document.getElementById('lb-help').getAttribute('iconCls')
})""")
exp1 = {
"mainZoneText": "Edit",
"hasArrowZone": True,
"menuAttr": "#mm",
"helpLinkbuttonPlain": True,
"helpLinkbuttonIcon": "icon-help",
}
cases.append({
"name": "splitbutton_dual_zone_structure",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
})
# Case 2: Main zone click fires primary action without opening menu; arrow opens menu
page.click("#sb-edit .s-btn-main")
after_main = page.evaluate("""() => ({
mainClicks: window.__mainClicks,
menuDisplayAfterMain: getComputedStyle(document.getElementById('mm')).display
})""")
page.click("#sb-edit .s-btn-downarrow")
after_arrow = page.evaluate("""() => ({
mainClicksAfterArrow: window.__mainClicks,
menuDisplayAfterArrow: getComputedStyle(document.getElementById('mm')).display
})""")
act2 = dict(after_main, **after_arrow)
exp2 = {
"mainClicks": 1,
"menuDisplayAfterMain": "none",
"mainClicksAfterArrow": 1,
"menuDisplayAfterArrow": "block",
}
cases.append({
"name": "splitbutton_main_click_vs_arrow_menu",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
})
# Case 3: Hover Open reveals nested submenu; click Firefox records selection and hides menu
page.hover("#item-open")
sub_visible = page.evaluate("() => getComputedStyle(document.getElementById('sub-open')).display === 'block'")
page.locator("#sub-open .menu-item", has_text="Firefox").click()
act3 = page.evaluate("""(subVis) => ({
submenuVisibleOnHover: subVis,
pickedItems: window.__menuPicks.slice(),
menuClosedAfterPick: getComputedStyle(document.getElementById('mm')).display === 'none'
})""", sub_visible)
exp3 = {
"submenuVisibleOnHover": True,
"pickedItems": ["Firefox"],
"menuClosedAfterPick": True,
}
cases.append({
"name": "splitbutton_nested_submenu_selection",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
核对点击主区仅触发主动作不弹菜单、点击箭头区展开菜单不触发主动作,以及悬停 Open 子菜单选择 Firefox 后自动关闭。
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1010.zip
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
MenuButton 点击整个按钮都会打开关联菜单;SplitButton 将按钮拆分为主操作区和下拉箭头区,点击主区执行默认动作,只有点击或悬停向下箭头区才展开下拉菜单。