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

折叠面板(Accordion)

核对 jQuery UI Accordion 的基础标题-面板结构、collapsible 折叠开关、自定义图标切换、heightStyle 高度策略、hoverintent 悬停展开与可排序分组面板。

学完这一章,你能够

  • 核对 jQuery UI Accordion 的基础标题-面板结构、collapsible 折叠开关、自定义图标切换、heightStyle 高度策略、hoverintent 悬停展开与可排序分组面板。

基础标记结构与可折叠模式

Accordion 部件用于在紧凑区域内按逻辑分组展示可切换展开的内容面板。基础 HTML 仅需成对排列标题元素(如 `<h3>`)和内容 `<div>`,即使关闭 JavaScript 仍能完整阅读内容;点击标题可展开对应内容并收起其余面板,亦可自定义悬停等触发事件(详见官方 Accordion Widget API)。

默认配置下 Accordion 始终保持恰好一个面板处于展开状态。若希望允许全部收起,将 `collapsible` 选项设为 `true`,再次点击当前激活标题即可折叠其内容区。本站离线 Chromium 实测:切换到第 2 项(索引 `1`)后,`collapsible: false` 下重复点击仍保持 `1`,改为 `collapsible: true` 后再次点击变为 `false`(全折叠)。

自定义标题图标与动态切换

借助 `icons` 选项可传入 `{ header, activeHeader }` 对象自定义未激活与激活状态的图标类名(可使用 UI CSS 框架自带图标类或自定义背景图类)。运行期间通过 `.accordion('option', 'icons', null)` 可移除图标,重新传入配置对象即可恢复。本站实测初始激活项应用 `ui-icon-circle-arrow-s`、折叠项应用 `ui-icon-circle-arrow-e`,点击切换按钮后清空为 `[None, None]`,再次恢复并切至第 2 项后图标类随激活状态互换。

高度策略:填充父容器与自适应内容

折叠面板默认横向铺满块级宽度;若要让面板纵向填满固定高度的外层容器,可配置 `heightStyle: 'fill'`,并在外层容器缩放(如配合 Resizable)时调用 `.accordion('refresh')` 重新计算内容区高度。

相反,若不希望所有面板按最高项等高对齐,可将 `heightStyle` 设为 `'content'`,令各面板保持自身内容的自然高度。本站实测:`heightStyle: 'fill'` 下将外部 `#resizer` 高度由 `220px` 增至 `300px` 并触发 `refresh` 后,展开面板高度精确增长 `80px`;`heightStyle: 'content'` 下含 7 条列表项的长面板高度显著高于单行短面板(差值大于 `60px`)。

悬停意图触发与面板重排

在常规点击基础上,通过 `event: 'click hoverintent'` 并注册自定义 `$.event.special.hoverintent` 事件,可在鼠标停顿 100ms 且位移曼哈顿距离小于 `7px` 时再展开对应标题,避免指针快速划过造成面板频繁闪烁(基础标记依然保持 `<h3>` 与 `<div>` 渐进增强)。

若要支持拖拽重排面板顺序,可将每组标题与内容包裹在 `.group` 容器中,对 Accordion 指定 `header: '> div > h3'`,并链式调用 `.sortable({ axis: 'y', handle: 'h3' })`,在 `stop` 回调中主动向标题派发 `focusout` 以清理旧版 IE 残留的聚焦样式。本站实测快速划过(位移 `17px`)不触发切换,平稳悬停(位移 `4px`、耗时 `110ms`)切换至索引 `1`;拖拽首组至末尾后顺序变为 `['g2', 'g3', 'g1']` 且 `focusout` 计数为 `1`。

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

含完整源码 · 251 行
展开查看收起
python
"""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()
核对 collapsible=false/true 差异、icons 置空与恢复、heightStyle fill 随容器增高 80px 与 content 自然高度、hoverintent 防误触及分组拖拽排序。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

Sortable 每次移动单个直接子元素;若不包裹,拖拽 h3 会导致标题与紧随的内容 div 分离。用 .group 包裹并指定 header 后,拖拽标题即可整体移动整组面板。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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