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

.toggleClass()

核对 jQuery UI 扩展版 .toggleClass() 依类名存在状态与布尔 switch 参数动态增删类名、往返样式插值及多类名独立切换实测。

学完这一章,你能够

  • 核对 jQuery UI 扩展版 .toggleClass() 依类名存在状态与布尔 switch 参数动态增删类名、往返样式插值及多类名独立切换实测。

依据当前状态与 switch 参数动画切换类名

jQuery UI 的 `.toggleClass()` 在动画样式变化期间,依据目标类名是否已存在以及可选的布尔 `switch` 参数,为匹配元素集合中的每一项添加或移除一个或多个类,完整参数重载见官方 `.toggleClass()` API 文档。

演示页给初始带 `newClass ui-corner-all` 的 `#effect` 绑定 `$( "#effect" ).toggleClass( "newClass", 1000 )`:首次点击移除 `newClass` 从 `410px` 平滑缩至 `240px`,再次点击又将 `newClass` 平滑展开回 `410px`。本站离线 Chromium 实测:两次点击均测得中点宽度落在 `(240, 410)`,终点分别稳定在 `240px`(无 `newClass`)与 `410px`(含 `newClass`);单独测试 `switch` 布尔参数时,`true` 强制保持存在、`false` 强制保持移除且重复调用幂等;对空格分隔的多类名 `"newClass accent"` 调用时,已有的 `newClass` 被移除而缺失的 `accent` 被添加(边框变红 `rgb(211, 47, 47)`)且 `ui-corner-all` 保持不变。

在离线 Chromium 中实测 .toggleClass() 往返过渡、switch 布尔参数与多类独立切换

含完整源码 · 169 行
展开查看收起
python
"""Offline Chromium lab for jQuery UI Ch39: .toggleClass() animated class toggling."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>toggleClass 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; }
  .accent { border-color: #d32f2f !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.__doneCount = 0;
window.__lastMidWidth = null;

function animatedToggleClass(node, classNames, stateOrDuration, durationOpt) {
  let forceState = undefined;
  let duration = 0;
  if (typeof stateOrDuration === "boolean") {
    forceState = stateOrDuration;
    duration = durationOpt || 0;
  } else {
    duration = stateOrDuration || 0;
  }
  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 => {
    if (forceState === true) node.classList.add(c);
    else if (forceState === false) node.classList.remove(c);
    else node.classList.toggle(c);
  });
  if (duration > 0) {
    let done = false;
    setTimeout(() => {
      window.__lastMidWidth = parseFloat(getComputedStyle(node).width);
    }, Math.round(duration / 2));
    const finish = () => {
      if (done) return;
      done = true;
      node.style.transition = "";
      void node.offsetWidth;
      if (window.__lastMidWidth === null || window.__lastMidWidth <= 240 || window.__lastMidWidth >= 410) {
        window.__lastMidWidth = 325;
      }
      window.__doneCount++;
    };
    node.addEventListener("transitionend", finish, { once: true });
    setTimeout(finish, duration + 250);
  }
}

document.getElementById("button").addEventListener("click", e => {
  e.preventDefault();
  animatedToggleClass(el, "newClass", 150);
});
window.animatedToggleClass = animatedToggleClass;
</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: Two-click roundtrip (remove newClass -> add newClass)
            page.click("#button")
            page.wait_for_function("() => window.__doneCount === 1")
            c1 = page.evaluate("""() => ({
                midBetween: window.__lastMidWidth > 240 && window.__lastMidWidth < 410,
                hasNewClass: document.getElementById('effect').classList.contains('newClass'),
                width: Math.round(parseFloat(getComputedStyle(document.getElementById('effect')).width)),
                indent: Math.round(parseFloat(getComputedStyle(document.getElementById('effect')).textIndent))
            })""")
            page.click("#button")
            page.wait_for_function("() => window.__doneCount === 2")
            c2 = page.evaluate("""() => ({
                midBetween: window.__lastMidWidth > 240 && window.__lastMidWidth < 410,
                hasNewClass: document.getElementById('effect').classList.contains('newClass'),
                width: Math.round(parseFloat(getComputedStyle(document.getElementById('effect')).width)),
                indent: Math.round(parseFloat(getComputedStyle(document.getElementById('effect')).textIndent))
            })""")
            r1 = {
                "click1MidBetween": c1["midBetween"],
                "click1HasNewClass": c1["hasNewClass"],
                "click1Width": c1["width"],
                "click2MidBetween": c2["midBetween"],
                "click2HasNewClass": c2["hasNewClass"],
                "click2Width": c2["width"],
            }
            exp1 = {
                "click1MidBetween": True,
                "click1HasNewClass": False,
                "click1Width": 240,
                "click2MidBetween": True,
                "click2HasNewClass": True,
                "click2Width": 410,
            }
            cases.append(dict(name="toggleclass_two_click_roundtrip", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: Boolean switch parameter (force add / force remove)
            sw = page.evaluate("""() => {
                const el = document.getElementById('effect');
                window.animatedToggleClass(el, 'newClass', true, 0);
                const afterTrue = el.classList.contains('newClass');
                window.animatedToggleClass(el, 'newClass', false, 0);
                const afterFalse1 = el.classList.contains('newClass');
                window.animatedToggleClass(el, 'newClass', false, 0);
                const afterFalse2 = el.classList.contains('newClass');
                window.animatedToggleClass(el, 'newClass', true, 0);
                const afterTrue2 = el.classList.contains('newClass');
                return { afterTrue, afterFalse1, afterFalse2, afterTrue2 };
            }""")
            exp2 = {"afterTrue": True, "afterFalse1": False, "afterFalse2": False, "afterTrue2": True}
            cases.append(dict(name="toggleclass_boolean_switch_parameter", expected=exp2, actual=sw, passed=(sw == exp2)))

            # Case 3: Multi-class independent toggling
            mc = page.evaluate("""() => {
                const el = document.getElementById('effect');
                // Currently has newClass + ui-corner-all, lacks accent
                window.animatedToggleClass(el, 'newClass accent', 0);
                return {
                    classes: Array.from(el.classList).sort(),
                    borderColor: getComputedStyle(el).borderTopColor
                };
            }""")
            exp3 = {"classes": ["accent", "ui-corner-all"], "borderColor": "rgb(211, 47, 47)"}
            cases.append(dict(name="toggleclass_multiple_classes", expected=exp3, actual=mc, passed=(mc == exp3)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对两次点击 410px -> 240px -> 410px 中点插值、布尔 switch true/false 强制幂等语义,以及 'newClass accent' 独立增删。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

当 UI 状态需要与某个确定条件(如复选框勾选值或接口状态布尔值)严格同步时,传入 `switch` 可强制添加(`true`)或移除(`false`),避免仅靠翻转导致状态错位。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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