蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-toggleclass.py
explore-example-toggleclass.py169 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/jqueryui-example-toggleclass-lab/explore-example-toggleclass.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-example-toggleclass.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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