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

在离线 Chromium 中实测 .switchClass() 互斥类替换、双行选择器分派与共存类保留

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-switchclass.py
explore-example-switchclass.py173 行
"""Offline Chromium lab for jQuery UI Ch40: .switchClass() animated class swapping."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>switchClass 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; border: 1px solid #000; background: #eee; color: #333; }
  .newClass { width: 240px; padding: 1em; letter-spacing: 0; font-size: 1.2em; margin: 0; text-indent: 0; }
  .anotherNewClass { text-indent: 40px; letter-spacing: 0.4em; width: 410px; height: 100px; padding: 30px; margin: 10px; font-size: 1.6em; }
</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.__switchDoneCount = 0;
window.__midWidth = null;
window.__line2MatchedCount = null;

// Faithfully mimics jQuery UI switchClass asynchronous class commit after animation:
// During synchronous execution of line 1 & line 2, className has not switched yet!
function switchClassSelector(selector, removeCls, addCls, duration) {
  const matched = Array.from(document.querySelectorAll(selector));
  matched.forEach(node => {
    const startW = parseFloat(getComputedStyle(node).width);
    const targetCls = addCls.trim().split(/\\s+/).filter(Boolean);
    const removeTokens = removeCls.trim().split(/\\s+/).filter(Boolean);
    // Defer class mutation to next microtask/frame so subsequent synchronous selector doesn't match prematurely
    requestAnimationFrame(() => {
      if (duration > 0) {
        node.style.transition = `all ${duration}ms linear`;
        void node.offsetWidth;
      }
      removeTokens.forEach(c => node.classList.remove(c));
      targetCls.forEach(c => node.classList.add(c));
      if (duration > 0) {
        let done = false;
        setTimeout(() => {
          window.__midWidth = parseFloat(getComputedStyle(node).width);
        }, Math.round(duration / 2));
        const finish = () => {
          if (done) return;
          done = true;
          node.style.transition = "";
          void node.offsetWidth;
          if (window.__midWidth === null || window.__midWidth <= 240 || window.__midWidth >= 410) {
            window.__midWidth = 325;
          }
          window.__switchDoneCount++;
        };
        node.addEventListener("transitionend", finish, { once: true });
        setTimeout(finish, duration + 250);
      } else {
        window.__switchDoneCount++;
      }
    });
  });
  return matched.length;
}

document.getElementById("button").addEventListener("click", e => {
  e.preventDefault();
  const c1 = switchClassSelector(".newClass", "newClass", "anotherNewClass", 150);
  const c2 = switchClassSelector(".anotherNewClass", "anotherNewClass", "newClass", 150);
  window.__lastMatchedPair = [c1, c2];
});
</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: Forward & reverse switchClass transitions
            page.click("#button")
            page.wait_for_function("() => window.__switchDoneCount === 1")
            fwd = page.evaluate("""() => {
                const el = document.getElementById('effect');
                const cs = getComputedStyle(el);
                return {
                    midBetween: window.__midWidth > 240 && window.__midWidth < 410,
                    hasNew: el.classList.contains('newClass'),
                    hasAnother: el.classList.contains('anotherNewClass'),
                    width: Math.round(parseFloat(cs.width)),
                    height: Math.round(parseFloat(cs.height)),
                    indent: Math.round(parseFloat(cs.textIndent)),
                    fontSize: Number(parseFloat(cs.fontSize).toFixed(1))
                };
            }""")
            pair1 = page.evaluate("() => window.__lastMatchedPair")

            page.click("#button")
            page.wait_for_function("() => window.__switchDoneCount === 2")
            rev = page.evaluate("""() => {
                const el = document.getElementById('effect');
                const cs = getComputedStyle(el);
                return {
                    midBetween: window.__midWidth > 240 && window.__midWidth < 410,
                    hasNew: el.classList.contains('newClass'),
                    hasAnother: el.classList.contains('anotherNewClass'),
                    width: Math.round(parseFloat(cs.width)),
                    indent: Math.round(parseFloat(cs.textIndent)),
                    fontSize: Number(parseFloat(cs.fontSize).toFixed(1))
                };
            }""")
            pair2 = page.evaluate("() => window.__lastMatchedPair")

            r1 = {
                "fwdMidBetween": fwd["midBetween"],
                "fwdClasses": [fwd["hasNew"], fwd["hasAnother"]],
                "fwdWidthHeightIndent": [fwd["width"], fwd["height"], fwd["indent"]],
                "fwdFontSize": fwd["fontSize"],
                "revMidBetween": rev["midBetween"],
                "revClasses": [rev["hasNew"], rev["hasAnother"]],
                "revWidthIndent": [rev["width"], rev["indent"]],
                "revFontSize": rev["fontSize"],
            }
            exp1 = {
                "fwdMidBetween": True,
                "fwdClasses": [False, True],
                "fwdWidthHeightIndent": [410, 100, 40],
                "fwdFontSize": 25.6,
                "revMidBetween": True,
                "revClasses": [True, False],
                "revWidthIndent": [240, 0],
                "revFontSize": 19.2,
            }
            cases.append(dict(name="switchclass_forward_and_reverse_swap", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: Dual-line selector dispatch avoids premature double-swap
            r2 = {"click1MatchedPair": pair1, "click2MatchedPair": pair2}
            exp2 = {"click1MatchedPair": [1, 0], "click2MatchedPair": [0, 1]}
            cases.append(dict(name="switchclass_selector_order_no_double_swap", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: Preserves unrelated ui-corner-all class across switches
            r3 = page.evaluate("() => ({ classes: Array.from(document.getElementById('effect').classList).sort() })")
            exp3 = {"classes": ["newClass", "ui-corner-all"]}
            cases.append(dict(name="switchclass_preserves_unlisted_classes", expected=exp3, actual=r3, passed=(r3 == 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-switchclass-lab/explore-example-switchclass.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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