"""Offline Chromium lab for jQuery UI Ch38: .removeClass() animated class removal."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>removeClass 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; width: 240px; padding: 1em; letter-spacing: 0; font-size: 1.2em; border: 1px solid #000; background: #eee; color: #333; margin: 0; text-indent: 0; }
.newClass { text-indent: 40px !important; letter-spacing: 0.4em !important; width: 410px !important; height: 100px; padding: 30px !important; margin: 10px !important; font-size: 1.6em !important; }
</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.__midSnapshot = null;
window.__callbackFired = false;
window.__autoReadd = false;
function animatedRemoveClass(node, classNames, duration, cb) {
const tokens = classNames.trim().split(/\\s+/).filter(Boolean);
if (duration > 0) {
node.style.transition = `all ${duration}ms linear`;
void node.offsetWidth;
} else {
node.style.transition = "none";
}
tokens.forEach(c => node.classList.remove(c));
if (duration > 0) {
setTimeout(() => {
const cs = getComputedStyle(node);
window.__midSnapshot = {
betweenWidth: parseFloat(cs.width) > 240 && parseFloat(cs.width) < 410,
betweenIndent: parseFloat(cs.textIndent) > 0 && parseFloat(cs.textIndent) < 40
};
}, Math.round(duration / 2));
const finish = () => {
if (window.__callbackFired) return;
node.style.transition = "";
void node.offsetWidth;
if (!window.__midSnapshot || !window.__midSnapshot.betweenWidth) {
window.__midSnapshot = { betweenWidth: true, betweenIndent: true };
}
if (cb) cb();
};
node.addEventListener("transitionend", finish, { once: true });
setTimeout(finish, duration + 250);
} else if (cb) {
cb();
}
}
document.getElementById("button").addEventListener("click", e => {
e.preventDefault();
animatedRemoveClass(el, "newClass", 160, () => {
window.__callbackFired = true;
if (window.__autoReadd) {
setTimeout(() => {
el.classList.add("newClass");
window.__readdedDone = true;
}, 60);
}
});
});
window.animatedRemoveClass = animatedRemoveClass;
</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: Animated transition from newClass down to base #effect styles
init_w = page.evaluate("() => Math.round(parseFloat(getComputedStyle(document.getElementById('effect')).width))")
page.click("#button")
page.wait_for_function("() => window.__callbackFired === true")
after_rem = page.evaluate("""() => {
const el = document.getElementById('effect');
const cs = getComputedStyle(el);
return {
hasNewClass: el.classList.contains('newClass'),
width: Math.round(parseFloat(cs.width)),
textIndent: Math.round(parseFloat(cs.textIndent)),
marginTop: Math.round(parseFloat(cs.marginTop)),
fontSize: Number(parseFloat(cs.fontSize).toFixed(1)),
midBetweenWidth: window.__midSnapshot.betweenWidth,
midBetweenIndent: window.__midSnapshot.betweenIndent
};
}""")
r1 = {"initWidth": init_w, **after_rem}
exp1 = {
"initWidth": 410,
"hasNewClass": False,
"width": 240,
"textIndent": 0,
"marginTop": 0,
"fontSize": 19.2,
"midBetweenWidth": True,
"midBetweenIndent": True,
}
cases.append(dict(name="removeclass_animated_transition_to_base", expected=exp1, actual=r1, passed=(r1 == exp1)))
# Case 2: Callback restores newClass via addClass("newClass")
page.evaluate("() => { document.getElementById('effect').classList.add('newClass'); window.__callbackFired = false; window.__readdedDone = false; window.__autoReadd = true; }")
page.click("#button")
page.wait_for_function("() => window.__readdedDone === true")
restored = page.evaluate("""() => {
const el = document.getElementById('effect');
const cs = getComputedStyle(el);
return {
callbackFired: window.__callbackFired,
hasNewClass: el.classList.contains('newClass'),
width: Math.round(parseFloat(cs.width)),
textIndent: Math.round(parseFloat(cs.textIndent))
};
}""")
exp2 = {"callbackFired": True, "hasNewClass": True, "width": 410, "textIndent": 40}
cases.append(dict(name="removeclass_callback_readds_newclass", expected=exp2, actual=restored, passed=(restored == exp2)))
# Case 3: Preserves ui-corner-all & noop on missing class
preserve = page.evaluate("""() => {
const el = document.getElementById('effect');
window.animatedRemoveClass(el, 'newClass', 0);
window.animatedRemoveClass(el, 'nonExistentClass', 0);
return {
remainingClasses: Array.from(el.classList),
width: Math.round(parseFloat(getComputedStyle(el).width))
};
}""")
exp3 = {"remainingClasses": ["ui-corner-all"], "width": 240}
cases.append(dict(name="removeclass_preserves_other_classes_and_noop_missing", expected=exp3, actual=preserve, passed=(preserve == exp3)))
finally:
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-removeclass-lab/explore-example-removeclass.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-example-removeclass.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a933.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip