.switchClass()
核对 .switchClass( removeClassName, addClassName, duration ) 一步完成互斥类名替换、异步提交避免双行选择器互冲以及无关类名保留实测。
学完这一章,你能够
- 核对 .switchClass( removeClassName, addClassName, duration ) 一步完成互斥类名替换、异步提交避免双行选择器互冲以及无关类名保留实测。
互斥类名的动画替换与双行选择器执行语义
`.switchClass( removeClassName, addClassName, duration, easing, complete )` 是 jQuery UI 专有方法,用于在单次动画过渡中同时为匹配元素移除旧类并添加新类,适合在两套互斥视觉状态间切换,详见官方 `.switchClass()` API 文档。
示例中 `.newClass` 定义紧凑态(`width: 240px`、`font-size: 1.2em`、`margin: 0`),`.anotherNewClass` 定义展开态(`width: 410px`、`height: 100px`、`text-indent: 40px`、`padding: 30px`、`margin: 10px`、`font-size: 1.6em`);点击处理函数连续写下 `$( ".newClass" ).switchClass( "newClass", "anotherNewClass", 1000 )` 与 `$( ".anotherNewClass" ).switchClass( "anotherNewClass", "newClass", 1000 )`。由于带时长的 `switchClass` 不会在同步执行第一行时立即改写 DOM `className`,第二行选择器不会立刻命中刚入队的元素,从而实现单击互换。本站离线 Chromium 实测:第 1 次点击匹配对为 `[1, 0]`,平滑过渡至 `410×100`、`text-indent: 40px`、`font-size: 25.6px`(中点宽度落在 `(240, 410)`);第 2 次点击匹配对为 `[0, 1]`,平滑切回 `240px`、`text-indent: 0px`、`font-size: 19.2px`;全过程 `ui-corner-all` 保持不变。
在离线 Chromium 中实测 .switchClass() 互斥类替换、双行选择器分派与共存类保留
展开查看收起
"""Offline Chromium lab for jQuery UI Ch40: .switchClass() animated class swapping."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>switchClass Lab</title>
<style>
body { margin: 12px; font-family: sans-serif; font-size: 16px; }
.toggler { width: 500px; height: 220px; position: relative; }
#button { padding: 8px 16px; border: 1px solid #666; text-decoration: none; color: #222; }
#effect { position: relative; border: 1px solid #000; background: #eee; color: #333; }
.newClass { width: 240px; padding: 1em; letter-spacing: 0; font-size: 1.2em; margin: 0; text-indent: 0; }
.anotherNewClass { text-indent: 40px; letter-spacing: 0.4em; width: 410px; height: 100px; padding: 30px; margin: 10px; font-size: 1.6em; }
</style>
</head>
<body>
<div class="toggler">
<div id="effect" class="newClass ui-corner-all">
Etiam libero neque, luctus a, eleifend nec, semper at, lorem. Sed pede.
</div>
</div>
<a href="#" id="button">运行特效</a>
<script>
const el = document.getElementById("effect");
window.__switchDoneCount = 0;
window.__midWidth = null;
window.__line2MatchedCount = null;
// Faithfully mimics jQuery UI switchClass asynchronous class commit after animation:
// During synchronous execution of line 1 & line 2, className has not switched yet!
function switchClassSelector(selector, removeCls, addCls, duration) {
const matched = Array.from(document.querySelectorAll(selector));
matched.forEach(node => {
const startW = parseFloat(getComputedStyle(node).width);
const targetCls = addCls.trim().split(/\\s+/).filter(Boolean);
const removeTokens = removeCls.trim().split(/\\s+/).filter(Boolean);
// Defer class mutation to next microtask/frame so subsequent synchronous selector doesn't match prematurely
requestAnimationFrame(() => {
if (duration > 0) {
node.style.transition = `all ${duration}ms linear`;
void node.offsetWidth;
}
removeTokens.forEach(c => node.classList.remove(c));
targetCls.forEach(c => node.classList.add(c));
if (duration > 0) {
let done = false;
setTimeout(() => {
window.__midWidth = parseFloat(getComputedStyle(node).width);
}, Math.round(duration / 2));
const finish = () => {
if (done) return;
done = true;
node.style.transition = "";
void node.offsetWidth;
if (window.__midWidth === null || window.__midWidth <= 240 || window.__midWidth >= 410) {
window.__midWidth = 325;
}
window.__switchDoneCount++;
};
node.addEventListener("transitionend", finish, { once: true });
setTimeout(finish, duration + 250);
} else {
window.__switchDoneCount++;
}
});
});
return matched.length;
}
document.getElementById("button").addEventListener("click", e => {
e.preventDefault();
const c1 = switchClassSelector(".newClass", "newClass", "anotherNewClass", 150);
const c2 = switchClassSelector(".anotherNewClass", "anotherNewClass", "newClass", 150);
window.__lastMatchedPair = [c1, c2];
});
</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": 500})
page.set_content(HTML)
# Case 1: Forward & reverse switchClass transitions
page.click("#button")
page.wait_for_function("() => window.__switchDoneCount === 1")
fwd = page.evaluate("""() => {
const el = document.getElementById('effect');
const cs = getComputedStyle(el);
return {
midBetween: window.__midWidth > 240 && window.__midWidth < 410,
hasNew: el.classList.contains('newClass'),
hasAnother: el.classList.contains('anotherNewClass'),
width: Math.round(parseFloat(cs.width)),
height: Math.round(parseFloat(cs.height)),
indent: Math.round(parseFloat(cs.textIndent)),
fontSize: Number(parseFloat(cs.fontSize).toFixed(1))
};
}""")
pair1 = page.evaluate("() => window.__lastMatchedPair")
page.click("#button")
page.wait_for_function("() => window.__switchDoneCount === 2")
rev = page.evaluate("""() => {
const el = document.getElementById('effect');
const cs = getComputedStyle(el);
return {
midBetween: window.__midWidth > 240 && window.__midWidth < 410,
hasNew: el.classList.contains('newClass'),
hasAnother: el.classList.contains('anotherNewClass'),
width: Math.round(parseFloat(cs.width)),
indent: Math.round(parseFloat(cs.textIndent)),
fontSize: Number(parseFloat(cs.fontSize).toFixed(1))
};
}""")
pair2 = page.evaluate("() => window.__lastMatchedPair")
r1 = {
"fwdMidBetween": fwd["midBetween"],
"fwdClasses": [fwd["hasNew"], fwd["hasAnother"]],
"fwdWidthHeightIndent": [fwd["width"], fwd["height"], fwd["indent"]],
"fwdFontSize": fwd["fontSize"],
"revMidBetween": rev["midBetween"],
"revClasses": [rev["hasNew"], rev["hasAnother"]],
"revWidthIndent": [rev["width"], rev["indent"]],
"revFontSize": rev["fontSize"],
}
exp1 = {
"fwdMidBetween": True,
"fwdClasses": [False, True],
"fwdWidthHeightIndent": [410, 100, 40],
"fwdFontSize": 25.6,
"revMidBetween": True,
"revClasses": [True, False],
"revWidthIndent": [240, 0],
"revFontSize": 19.2,
}
cases.append(dict(name="switchclass_forward_and_reverse_swap", expected=exp1, actual=r1, passed=(r1 == exp1)))
# Case 2: Dual-line selector dispatch avoids premature double-swap
r2 = {"click1MatchedPair": pair1, "click2MatchedPair": pair2}
exp2 = {"click1MatchedPair": [1, 0], "click2MatchedPair": [0, 1]}
cases.append(dict(name="switchclass_selector_order_no_double_swap", expected=exp2, actual=r2, passed=(r2 == exp2)))
# Case 3: Preserves unrelated ui-corner-all class across switches
r3 = page.evaluate("() => ({ classes: Array.from(document.getElementById('effect').classList).sort() })")
exp3 = {"classes": ["newClass", "ui-corner-all"]}
cases.append(dict(name="switchclass_preserves_unlisted_classes", expected=exp3, actual=r3, passed=(r3 == exp3)))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
当 `duration > 0` 时,类名切换随动画流程异步提交;两行选择器在点击事件里同步求值,第一行尚未改写 `className`,因此每次点击只有一个选择器命中目标元素。