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

在离线 Chromium 中验证 Accordion 折叠开关、图标切换、高度策略与分组排序

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-accordion.py
explore-example-accordion.py251 行
"""Offline Playwright Chromium lab for jQuery UI Ch 22: Accordion."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Accordion Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; }
  .acc h3 { margin: 0; padding: 8px 10px; background: #eee; border: 1px solid #ccc; cursor: pointer; font-size: 14px; line-height: 18px; }
  .acc .panel { border: 1px solid #ccc; border-top: 0; padding: 8px; overflow: auto; box-sizing: border-box; }
  .acc .panel.hidden { display: none; }
  #resizer { width: 350px; height: 220px; padding: 10px; border: 1px solid #999; box-sizing: border-box; }
  .icon { display: inline-block; width: 12px; margin-right: 6px; }
</style>
</head>
<body>
<div id="acc-basic" class="acc">
  <h3>部分 1</h3><div class="panel"><p>Panel 1 body</p></div>
  <h3>部分 2</h3><div class="panel"><p>Panel 2 body</p></div>
  <h3>部分 3</h3><div class="panel"><p>Panel 3 body</p></div>
</div>

<div id="acc-icons" class="acc" style="margin-top:12px;">
  <h3>节 A</h3><div class="panel"><p>A</p></div>
  <h3>节 B</h3><div class="panel"><p>B</p></div>
</div>
<button id="toggle-icons">切换图标</button>

<div id="resizer" style="margin-top:12px;">
  <div id="acc-fill" class="acc">
    <h3>填充 1</h3><div class="panel"><p>Short text</p></div>
    <h3>填充 2</h3><div class="panel"><p>Short text 2</p></div>
  </div>
</div>

<div id="acc-content" class="acc" style="margin-top:12px; width: 350px;">
  <h3>短内容</h3><div class="panel"><p>One line</p></div>
  <h3>长内容</h3><div class="panel"><ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li></ul></div>
</div>

<div id="acc-hover" class="acc" style="margin-top:12px;">
  <h3>悬停 1</h3><div class="panel"><p>H1</p></div>
  <h3>悬停 2</h3><div class="panel"><p>H2</p></div>
</div>

<div id="acc-sort" class="acc" style="margin-top:12px;">
  <div class="group" data-g="g1"><h3>组 1</h3><div class="panel"><p>G1</p></div></div>
  <div class="group" data-g="g2"><h3>组 2</h3><div class="panel"><p>G2</p></div></div>
  <div class="group" data-g="g3"><h3>组 3</h3><div class="panel"><p>G3</p></div></div>
</div>

<script>
function initAccordion(rootId, opts = {}) {
  const root = document.getElementById(rootId);
  const headers = opts.grouped
    ? Array.from(root.querySelectorAll(":scope > .group > h3"))
    : Array.from(root.querySelectorAll(":scope > h3"));
  const panels = headers.map(h => h.nextElementSibling);
  const state = {
    active: opts.active !== undefined ? opts.active : 0,
    collapsible: !!opts.collapsible,
    heightStyle: opts.heightStyle || "auto",
    icons: opts.icons || null,
    focusoutCount: 0,
  };

  function applyIcons() {
    headers.forEach((h, idx) => {
      const old = h.querySelector(".icon");
      if (old) old.remove();
      if (state.icons) {
        const sp = document.createElement("span");
        sp.className = "icon " + (idx === state.active ? state.icons.activeHeader : state.icons.header);
        h.prepend(sp);
      }
    });
  }

  function applyHeights() {
    if (state.heightStyle === "fill") {
      const parentStyle = getComputedStyle(root.parentElement);
      const innerH = root.parentElement.clientHeight - parseFloat(parentStyle.paddingTop) - parseFloat(parentStyle.paddingBottom);
      const headersH = headers.reduce((s, h) => s + h.getBoundingClientRect().height, 0);
      const targetH = Math.max(20, Math.round(innerH - headersH));
      panels.forEach(p => { p.style.height = targetH + "px"; });
    } else if (state.heightStyle === "content") {
      panels.forEach(p => { p.style.height = "auto"; });
    }
  }

  function render() {
    panels.forEach((p, idx) => {
      p.classList.toggle("hidden", idx !== state.active);
    });
    applyIcons();
    applyHeights();
  }

  headers.forEach((h, idx) => {
    h.addEventListener("click", () => {
      if (state.active === idx) {
        if (state.collapsible) state.active = false;
      } else {
        state.active = idx;
      }
      render();
    });
    h.addEventListener("focusout", () => { state.focusoutCount += 1; });
  });

  render();
  return {
    state,
    setOption(k, v) { state[k] = v; render(); },
    refresh() { applyHeights(); },
    activate(idx) { state.active = idx; render(); },
    getIconClasses() {
      return headers.map(h => {
        const sp = h.querySelector(".icon");
        return sp ? sp.className : null;
      });
    },
    getVisiblePanelHeights() {
      return panels.map(p => p.classList.contains("hidden") ? 0 : Math.round(p.getBoundingClientRect().height));
    },
    reorderGroup(fromIdx, toIdx) {
      const groups = Array.from(root.querySelectorAll(":scope > .group"));
      const item = groups[fromIdx];
      const ref = groups[toIdx];
      if (fromIdx < toIdx) root.insertBefore(item, ref.nextSibling);
      else root.insertBefore(item, ref);
      item.querySelector("h3").dispatchEvent(new Event("focusout"));
      return Array.from(root.querySelectorAll(":scope > .group")).map(g => g.dataset.g);
    }
  };
}

window.accBasic = initAccordion("acc-basic", { collapsible: false });
const customIcons = { header: "ui-icon-circle-arrow-e", activeHeader: "ui-icon-circle-arrow-s" };
window.accIcons = initAccordion("acc-icons", { icons: customIcons });
document.getElementById("toggle-icons").addEventListener("click", () => {
  window.accIcons.setOption("icons", window.accIcons.state.icons ? null : customIcons);
});
window.accFill = initAccordion("acc-fill", { heightStyle: "fill" });
window.accContent = initAccordion("acc-content", { heightStyle: "content" });
window.accHover = initAccordion("acc-hover", {});
window.accSort = initAccordion("acc-sort", { grouped: true });

// Hoverintent check: movement < 7px after 100ms triggers activation
window.testHoverIntent = (dx, dy, elapsedMs, targetIdx) => {
  if (elapsedMs >= 100 && (Math.abs(dx) + Math.abs(dy)) < 7) {
    window.accHover.activate(targetIdx);
    return true;
  }
  return false;
};
</script>
</body>
</html>
"""


def main():
    cases = []
    with sync_playwright() as p:
        try:
            browser = p.chromium.launch(headless=True)
        except Exception:
            browser = p.chromium.launch(headless=True, channel="chrome")
        page = browser.new_page(viewport={"width": 1024, "height": 900})
        page.set_content(HTML_DOC)

        # Case 1: Default open + switch + collapsible false vs true
        page.click("#acc-basic h3:nth-of-type(2)")
        after_switch = page.evaluate("() => window.accBasic.state.active")
        page.click("#acc-basic h3:nth-of-type(2)")
        still_open = page.evaluate("() => window.accBasic.state.active")
        page.evaluate("() => window.accBasic.setOption('collapsible', true)")
        page.click("#acc-basic h3:nth-of-type(2)")
        collapsed_all = page.evaluate("() => window.accBasic.state.active")
        res1 = {
            "afterSwitch": after_switch,
            "nonCollapsibleClickSame": still_open,
            "collapsibleClickSame": collapsed_all,
        }
        exp1 = {"afterSwitch": 1, "nonCollapsibleClickSame": 1, "collapsibleClickSame": False}
        cases.append(dict(name="accordion_default_and_collapsible", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Custom icons and toggle button
        init_icons = page.evaluate("() => window.accIcons.getIconClasses()")
        page.click("#toggle-icons")
        removed_icons = page.evaluate("() => window.accIcons.getIconClasses()")
        page.click("#toggle-icons")
        page.click("#acc-icons h3:nth-of-type(2)")
        switched_icons = page.evaluate("() => window.accIcons.getIconClasses()")
        res2 = {"init": init_icons, "removed": removed_icons, "switched": switched_icons}
        exp2 = {
            "init": ["icon ui-icon-circle-arrow-s", "icon ui-icon-circle-arrow-e"],
            "removed": [None, None],
            "switched": ["icon ui-icon-circle-arrow-e", "icon ui-icon-circle-arrow-s"],
        }
        cases.append(dict(name="accordion_custom_icons_and_toggle", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: heightStyle fill + resize refresh vs heightStyle content
        res3 = page.evaluate("""() => {
            const fillInitial = window.accFill.getVisiblePanelHeights()[0];
            document.getElementById("resizer").style.height = "300px";
            window.accFill.refresh();
            const fillAfterResize = window.accFill.getVisiblePanelHeights()[0];
            const contentShort = window.accContent.getVisiblePanelHeights()[0];
            window.accContent.activate(1);
            const contentTall = window.accContent.getVisiblePanelHeights()[1];
            return {
                fillGrewBy: fillAfterResize - fillInitial,
                fillInitialPositive: fillInitial > 100,
                contentTallGreaterThanShort: contentTall > contentShort + 60
            };
        }""")
        exp3 = {"fillGrewBy": 80, "fillInitialPositive": True, "contentTallGreaterThanShort": True}
        cases.append(dict(name="accordion_height_style_fill_and_content", expected=exp3, actual=res3, passed=(res3 == exp3)))

        # Case 4: Hoverintent threshold + sortable grouped panels with focusout
        res4 = page.evaluate("""() => {
            const fastSweep = window.testHoverIntent(12, 5, 100, 1);
            const afterFast = window.accHover.state.active;
            const steadyHover = window.testHoverIntent(2, 2, 110, 1);
            const afterSteady = window.accHover.state.active;
            const newOrder = window.accSort.reorderGroup(0, 2);
            const focusoutFired = window.accSort.state.focusoutCount;
            return { fastSweep, afterFast, steadyHover, afterSteady, newOrder, focusoutFired };
        }""")
        exp4 = {
            "fastSweep": False,
            "afterFast": 0,
            "steadyHover": True,
            "afterSteady": 1,
            "newOrder": ["g2", "g3", "g1"],
            "focusoutFired": 1,
        }
        cases.append(dict(name="accordion_hoverintent_and_sortable", expected=exp4, actual=res4, passed=(res4 == exp4)))

        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-accordion-lab/explore-example-accordion.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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