选择(Selectable)
核对 Selectable 交互的默认框选与 Ctrl 非相邻多选、CSS 浮动网格排布选择以及 stop 事件序列化选中项索引的完整流程。
学完这一章,你能够
- 核对 Selectable 交互的默认框选与 Ctrl 非相邻多选、CSS 浮动网格排布选择以及 stop 事件序列化选中项索引的完整流程。
默认框选与 Ctrl 非相邻多选
Selectable 交互支持用户使用鼠标单击或拖拽套索框选单个元素或一组元素,详细配置与事件列表对应官方可选择小部件(Selectable Widget)文档。
对有序列表等容器调用 `.selectable()` 后,拖动鼠标框选区域内的条目在过程阶段获得 `.ui-selecting` 状态类,松手后转为 `.ui-selected` 最终选中类;按住 `Ctrl`(macOS 为 `Cmd`)键点击则可追加选择不相邻的多个条目。本站离线 Chromium 实测:鼠标套索划过 Item 2 至 Item 4 期间观测到 `.ui-selecting` 生效、松手确认选中 `["Item 2", "Item 3", "Item 4"]`;随后按住 `Control` 点击 Item 6 追加为 `["Item 2", "Item 3", "Item 4", "Item 6"]`;普通单击 Item 1 则重置为 `["Item 1"]`。
网格布局选择与 stop 事件结果序列化
Selectable 本身不绑定特定排布方式——只需用 CSS 为各 `<li>` 设置统一宽高与浮动布局(例如定宽容器配合等尺寸方块),即可在二维网格中用套索跨行跨列框选条目。本站 Chromium 实测在 4 列 × 3 行(编号 `1`–`12`)网格中自左上角框选 2×2 区域,精确选中 `["1", "2", "5", "6"]`。
在初始化时监听 `stop` 事件回调,可于每次框选或点击结束后清空结果容器,遍历当前带 `.ui-selected` 类名的条目并计算其在列表中的索引值,以可读文本反馈给用户或拼装为待提交的数据字符串。本站 Chromium 实测套索选中第 1–3 项再按住 `Control` 点击第 5 项后,`stop` 回调即时向 `#select-result` 写入 `"#1 #2 #3 #5"`。
在离线 Chromium 中实测 Selectable 框选、Ctrl 多选、网格框选与 stop 序列化
"""Offline Chromium lab for jQuery UI Ch20: Selectable interactions (default, grid, serialize)."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Selectable Lab</title>
<style>
* { box-sizing: border-box; }
body { margin: 8px; font-family: sans-serif; user-select: none; }
.ui-selecting { background: #FECA40 !important; }
.ui-selected { background: #F39814 !important; color: white !important; }
#sel-default, #sel-serialize { list-style: none; margin: 0 0 12px 0; padding: 0; width: 240px; }
#sel-default li, #sel-serialize li { margin: 3px; padding: 4px 8px; height: 26px; border: 1px solid #bbb; background: #fff; }
#sel-grid { list-style: none; margin: 0 0 12px 0; padding: 0; width: 440px; overflow: hidden; }
#sel-grid li { margin: 3px; padding: 1px; float: left; width: 100px; height: 60px; font-size: 24px; text-align: center; line-height: 58px; border: 1px solid #bbb; background: #f8f8f8; }
#lasso { position: fixed; border: 1px dashed #333; background: rgba(33,150,243,0.12); pointer-events: none; display: none; }
</style>
</head>
<body>
<ol id="sel-default">
<li>Item 1</li><li>Item 2</li><li>Item 3</li><li>Item 4</li><li>Item 5</li><li>Item 6</li><li>Item 7</li>
</ol>
<ol id="sel-grid">
<li>1</li><li>2</li><li>3</li><li>4</li>
<li>5</li><li>6</li><li>7</li><li>8</li>
<li>9</li><li>10</li><li>11</li><li>12</li>
</ol>
<p id="feedback"><span>您已经选择了:</span><span id="select-result">无</span></p>
<ol id="sel-serialize">
<li>Item 1</li><li>Item 2</li><li>Item 3</li><li>Item 4</li><li>Item 5</li><li>Item 6</li>
</ol>
<div id="lasso"></div>
<script>
function rectIntersects(a, b) {
return !(a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom);
}
function makeSelectable(ol, opts = {}) {
const lasso = document.getElementById("lasso");
let state = null;
ol.addEventListener("mousedown", e => {
const items = Array.from(ol.querySelectorAll("li"));
const keepPrev = e.ctrlKey || e.metaKey;
state = { sx: e.clientX, sy: e.clientY, keepPrev, moved: false, items };
if (!keepPrev) {
items.forEach(li => li.classList.remove("ui-selected", "ui-selecting"));
}
const targetLi = e.target.closest("li");
if (targetLi && ol.contains(targetLi)) {
targetLi.classList.add("ui-selecting");
window.__sawSelectingClass = true;
}
});
window.addEventListener("mousemove", e => {
if (!state) return;
if (Math.hypot(e.clientX - state.sx, e.clientY - state.sy) >= 3) {
state.moved = true;
}
const left = Math.min(state.sx, e.clientX);
const top = Math.min(state.sy, e.clientY);
const width = Math.abs(e.clientX - state.sx);
const height = Math.abs(e.clientY - state.sy);
lasso.style.display = "block";
lasso.style.left = left + "px";
lasso.style.top = top + "px";
lasso.style.width = width + "px";
lasso.style.height = height + "px";
const lr = { left, top, right: left + width, bottom: top + height };
state.items.forEach(li => {
const hit = rectIntersects(lr, li.getBoundingClientRect());
if (hit) {
li.classList.add("ui-selecting");
window.__sawSelectingClass = true;
} else {
li.classList.remove("ui-selecting");
}
});
});
window.addEventListener("mouseup", () => {
if (!state) return;
const s = state;
state = null;
lasso.style.display = "none";
s.items.forEach(li => {
if (li.classList.contains("ui-selecting")) {
li.classList.remove("ui-selecting");
li.classList.add("ui-selected");
}
});
if (opts.stop) opts.stop.call(ol);
});
}
makeSelectable(document.getElementById("sel-default"));
makeSelectable(document.getElementById("sel-grid"));
makeSelectable(document.getElementById("sel-serialize"), {
stop() {
const result = document.getElementById("select-result");
result.textContent = "";
const all = Array.from(this.querySelectorAll("li"));
const selected = Array.from(this.querySelectorAll(".ui-selected"));
const tokens = selected.map(li => "#" + (all.indexOf(li) + 1));
result.textContent = tokens.join(" ");
}
});
</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(viewport={"width": 800, "height": 820})
page.set_content(HTML)
# Case 1: Default lasso + Ctrl+click multi-select + single click reset
li2 = page.locator("#sel-default li").nth(1).bounding_box()
li4 = page.locator("#sel-default li").nth(3).bounding_box()
page.mouse.move(li2["x"] + 15, li2["y"] + 8)
page.mouse.down()
page.mouse.move(li4["x"] + 60, li4["y"] + 14, steps=4)
page.mouse.up()
after_lasso = page.evaluate("() => Array.from(document.querySelectorAll('#sel-default li.ui-selected')).map(e => e.textContent)")
li6 = page.locator("#sel-default li").nth(5).bounding_box()
page.keyboard.down("Control")
page.mouse.click(li6["x"] + 20, li6["y"] + 10)
page.keyboard.up("Control")
after_ctrl = page.evaluate("() => Array.from(document.querySelectorAll('#sel-default li.ui-selected')).map(e => e.textContent)")
li1 = page.locator("#sel-default li").nth(0).bounding_box()
page.mouse.click(li1["x"] + 20, li1["y"] + 10)
after_single = page.evaluate("() => Array.from(document.querySelectorAll('#sel-default li.ui-selected')).map(e => e.textContent)")
saw_selecting = page.evaluate("() => Boolean(window.__sawSelectingClass)")
r1 = {
"sawSelecting": saw_selecting,
"afterLasso": after_lasso,
"afterCtrlClick": after_ctrl,
"afterSingleClick": after_single,
}
exp1 = {
"sawSelecting": True,
"afterLasso": ["Item 2", "Item 3", "Item 4"],
"afterCtrlClick": ["Item 2", "Item 3", "Item 4", "Item 6"],
"afterSingleClick": ["Item 1"],
}
cases.append(dict(name="default_lasso_and_ctrl_multiselect", expected=exp1, actual=r1, passed=(r1 == exp1)))
# Case 2: Grid layout 2x2 lasso (tiles 1, 2, 5, 6)
t1 = page.locator("#sel-grid li").nth(0).bounding_box()
t6 = page.locator("#sel-grid li").nth(5).bounding_box()
page.mouse.move(t1["x"] + 20, t1["y"] + 15)
page.mouse.down()
page.mouse.move(t6["x"] + 50, t6["y"] + 30, steps=4)
page.mouse.up()
grid_selected = page.evaluate("() => Array.from(document.querySelectorAll('#sel-grid li.ui-selected')).map(e => e.textContent)")
r2 = {"gridSelected": grid_selected}
exp2 = {"gridSelected": ["1", "2", "5", "6"]}
cases.append(dict(name="grid_layout_lasso_selection", expected=exp2, actual=r2, passed=(r2 == exp2)))
# Case 3: Serialize stop callback
s1 = page.locator("#sel-serialize li").nth(0).bounding_box()
s3 = page.locator("#sel-serialize li").nth(2).bounding_box()
page.mouse.move(s1["x"] + 20, s1["y"] + 10)
page.mouse.down()
page.mouse.move(s3["x"] + 60, s3["y"] + 14, steps=4)
page.mouse.up()
s5 = page.locator("#sel-serialize li").nth(4).bounding_box()
page.keyboard.down("Control")
page.mouse.click(s5["x"] + 20, s5["y"] + 10)
page.keyboard.up("Control")
r3 = {"serialized": page.locator("#select-result").text_content()}
exp3 = {"serialized": "#1 #2 #3 #5"}
cases.append(dict(name="serialize_stop_event_feedback", expected=exp3, actual=r3, passed=(r3 == exp3)))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对套索划选 Item 2-4 伴随 .ui-selecting 到 .ui-selected 切换、Ctrl 点击追加 Item 6、网格 2x2 选中 ['1','2','5','6'],以及 stop 回调序列化输出 '#1 #2 #3 #5'。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:b89abef1db1d1f988b751d1b09ed986a55177308f290da60c5ce86ec34979c5e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:52fa3d8f047e05f38349011b2b8215a5f9372232b48905143d0fe4e063dc1f4d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Selectable 序列化示例中,为何选择在 `stop` 事件而非 `selecting` 事件中收集并提交最终选中项索引?
展开参考解答
`selecting` 在鼠标拖动套索期间会高频反复触发且条目可能被移出选区;`stop` 仅在一次选择操作完全结束、`.ui-selected` 集合稳定后触发一次,能避免中间态抖动与重复写入。