"""Offline Chromium lab for jQuery UI Ch37: .addClass() animated class addition."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>addClass 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 { width: 240px; padding: 1em; font-size: 1.2em; border: 1px solid #000; background: #eee; color: #333; margin: 0; text-indent: 0; letter-spacing: 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; }
.highlight-box { background: #ffe082 !important; }
</style>
</head>
<body>
<div class="toggler">
<div id="effect" class="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;
function animatedAddClass(node, classNames, duration, cb) {
const tokens = classNames.trim().split(/\\s+/).filter(Boolean);
const startWidth = parseFloat(getComputedStyle(node).width);
const startIndent = parseFloat(getComputedStyle(node).textIndent);
if (duration > 0) {
node.style.transition = `all ${duration}ms linear`;
} else {
node.style.transition = "none";
}
tokens.forEach(c => node.classList.add(c));
if (duration > 0) {
setTimeout(() => {
const cs = getComputedStyle(node);
window.__midSnapshot = {
width: parseFloat(cs.width),
textIndent: parseFloat(cs.textIndent),
betweenWidth: parseFloat(cs.width) > startWidth && parseFloat(cs.width) < 410,
betweenIndent: parseFloat(cs.textIndent) > startIndent && parseFloat(cs.textIndent) < 40
};
}, Math.round(duration / 2));
setTimeout(() => {
node.style.transition = "";
if (cb) cb();
}, duration + 30);
} else if (cb) {
cb();
}
}
window.__autoRevert = true;
document.getElementById("button").addEventListener("click", e => {
e.preventDefault();
animatedAddClass(el, "newClass", 160, () => {
window.__callbackFired = true;
if (window.__autoRevert) {
setTimeout(() => {
el.classList.remove("newClass");
window.__revertedDone = true;
}, 60);
}
});
});
window.animatedAddClass = animatedAddClass;
</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 midpoint & final styles of addClass("newClass", duration)
page.evaluate("() => { window.__autoRevert = false; }")
init_vals = page.evaluate("""() => {
const cs = getComputedStyle(document.getElementById('effect'));
return { width: Math.round(parseFloat(cs.width)), textIndent: Math.round(parseFloat(cs.textIndent)), fontSize: Number(parseFloat(cs.fontSize).toFixed(1)) };
}""")
page.click("#button")
page.wait_for_function("() => window.__callbackFired === true")
final_vals = page.evaluate("""() => {
const el = document.getElementById('effect');
const cs = getComputedStyle(el);
return {
hasNewClass: el.classList.contains('newClass'),
width: Math.round(parseFloat(cs.width)),
height: Math.round(parseFloat(cs.height)),
textIndent: Math.round(parseFloat(cs.textIndent)),
paddingTop: Math.round(parseFloat(cs.paddingTop)),
marginTop: Math.round(parseFloat(cs.marginTop)),
fontSize: Number(parseFloat(cs.fontSize).toFixed(1)),
midBetweenWidth: window.__midSnapshot.betweenWidth,
midBetweenIndent: window.__midSnapshot.betweenIndent
};
}""")
r1 = {"initWidth": init_vals["width"], "initFontSize": init_vals["fontSize"], **final_vals}
exp1 = {
"initWidth": 240,
"initFontSize": 19.2,
"hasNewClass": True,
"width": 410,
"height": 100,
"textIndent": 40,
"paddingTop": 30,
"marginTop": 10,
"fontSize": 25.6,
"midBetweenWidth": True,
"midBetweenIndent": True,
}
cases.append(dict(name="addclass_animated_midpoint_and_final_styles", expected=exp1, actual=r1, passed=(r1 == exp1)))
# Case 2: Callback triggers removeClass("newClass") revert
page.evaluate("() => { document.getElementById('effect').classList.remove('newClass'); window.__callbackFired = false; window.__revertedDone = false; window.__autoRevert = true; }")
page.click("#button")
page.wait_for_function("() => window.__revertedDone === true")
rev_vals = 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": False, "width": 240, "textIndent": 0}
cases.append(dict(name="addclass_callback_auto_removeclass", expected=exp2, actual=rev_vals, passed=(rev_vals == exp2)))
# Case 3: Idempotent addClass & space-separated multi-class addition
multi = page.evaluate("""() => {
const el = document.getElementById('effect');
window.animatedAddClass(el, 'newClass highlight-box', 0);
window.animatedAddClass(el, 'newClass', 0);
const classes = Array.from(el.classList).sort();
return {
classes,
bg: getComputedStyle(el).backgroundColor
};
}""")
exp3 = {"classes": ["highlight-box", "newClass", "ui-corner-all"], "bg": "rgb(255, 224, 130)"}
cases.append(dict(name="addclass_idempotent_and_multi_class", expected=exp3, actual=multi, passed=(multi == 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-addclass-lab/explore-example-addclass.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-example-addclass.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a920.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip