.removeClass()
核对 jQuery UI 扩展版 .removeClass( className, duration, callback ) 平滑退回基础样式、回调重新加回类名以及保留其他共存类名的行为。
学完这一章,你能够
- 核对 jQuery UI 扩展版 .removeClass( className, duration, callback ) 平滑退回基础样式、回调重新加回类名以及保留其他共存类名的行为。
带动画过渡的 .removeClass() 样式还原
jQuery UI 扩展的 `.removeClass()` 会在指定动画时长内移除元素上的一个或多个 CSS 类,并将原本由该类施加的尺寸、间距与排版属性平滑插值回基础样式,详情参考官方 `.removeClass()` API 文档。
示例中 `#effect` 初始即带有 `newClass ui-corner-all`(宽 `410px`、高 `100px`、缩进 `40px`、字号 `1.6em`);点击按钮调用 `$( "#effect" ).removeClass( "newClass", 1000, callback )` 后,盒模型平滑收缩回 `#effect` 基础样式(宽 `240px`、缩进 `0`、字距 `0`、字号 `1.2em`),结束后 `callback` 延时调用 `addClass( "newClass" )` 重新恢复以便重复演示。本站离线 Chromium 实测:动画中点宽度处于 `(240, 410)` 且缩进处于 `(0, 40)`,移除完成后准确落回 `width: 240px`、`text-indent: 0px`、`margin: 0px`、`font-size: 19.2px`;回调触发后复原 `newClass` 与 `410px` 宽;且移除目标类或不存在的类名时,原有 `ui-corner-all` 类完好保留。
在离线 Chromium 中实测 .removeClass() 平滑退回基础样式、回调加回与共存类保护
"""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()
- 核对移除 newClass 中点插值与终点回归 240px / 缩进 0 / 字号 19.2px、回调恢复 410px,以及移除不存在类名时保留 ui-corner-all。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:b020be073e2d2abac9778dde914d44e0af31197566cc70ed022d356f3ef40942
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:772928482d7a6f5419de26a8f559b0739b80f3980a39bbc6c3840c3ce4fde050
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
当元素同时拥有 `newClass ui-corner-all` 时,执行 `.removeClass( "newClass", 1000 )` 会影响 `ui-corner-all` 吗?
展开参考解答
不会。`.removeClass()` 只移除参数中明确列出的类名及其对应的样式差异,其他共存类名(如 `ui-corner-all`)保持不变。