蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery UI 教程目录 43章
jQuery UI / LEARN BY DOING

.addClass()

核对 jQuery UI 扩展版 .addClass( className, duration, callback ) 触发的平滑样式过渡、中间帧插值、回调自动移除类名及多类名幂等行为。

学完这一章,你能够

  • 核对 jQuery UI 扩展版 .addClass( className, duration, callback ) 触发的平滑样式过渡、中间帧插值、回调自动移除类名及多类名幂等行为。

带动画过渡的 .addClass() 样式切换

jQuery UI 对原生 jQuery `.addClass()` 进行了动画增强:传入时长与回调参数后,为匹配元素添加指定 CSS 类时不会瞬间跳变,而是将目标类带来的可动画样式属性在指定时长内平滑过渡,详见官方 `.addClass()` API 文档。

示例中 `#effect` 初始宽度 `240px`、字号 `1.2em`(基准 `16px` 下为 `19.2px`);点击按钮执行 `$( "#effect" ).addClass( "newClass", 1000, callback )` 后,元素在过渡期内同步展开至 `.newClass` 定义的 `width: 410px`、`height: 100px`、`text-indent: 40px`、`letter-spacing: .4em`、`padding: 30px`、`margin: 10px` 与 `font-size: 1.6em`(`25.6px`),随后 `callback` 延时调用 `removeClass( "newClass" )` 复原。本站离线 Chromium 实测:过渡中点宽度严格落在 `(240, 410)` 且首行缩进落在 `(0, 40)`,终点准确达到 `410×100`、`text-indent: 40px`、`padding: 30px`、`margin: 10px`、`font-size: 25.6px`;回调执行后恢复 `240px` 与 `text-indent: 0px`;同时验证重复添加类名幂等且支持空格分隔同时添加多个类名。

在离线 Chromium 中实测 .addClass() 样式插值、回调复原与多类名添加

含完整源码 · 172 行
展开查看收起
python
"""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()
核对添加 newClass 期间宽度与缩进中点插值、终点 410×100 / 缩进 40px / 字号 25.6px、回调自动 removeClass 恢复 240px,以及多类名幂等添加。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a920.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a920.zip

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

外观样式全部声明在 CSS 类中,脚本只需控制语义类名与过渡时长,实现表现与逻辑解耦且更易维护主题与响应式覆盖。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习