折叠

使用几个类和我们的 JavaScript 插件,在项目中切换内容的可见性。

Requires JS
Layer: components

工作原理

折叠 JavaScript 插件用于显示和隐藏内容。按钮或锚点用作触发器,映射到你要切换的特定元素。该插件只添加和移除 .show——CSS 会从 0 到内容尺寸对大小进行动画处理。鉴于 CSS 处理动画的方式,你无法在 .collapse 元素上使用 padding。相反,请将该类用作独立的包装元素。

动画需要 interpolate-size。不支持它的浏览器会立即打开和关闭元素。请参阅过渡以更改时序或移除它。

此组件的动画效果取决于 prefers-reduced-motion 媒体查询。请参阅无障碍文档中的减少动态效果章节。

示例

点击下面的按钮,通过类更改显示和隐藏另一个元素:

  • .collapse 隐藏内容
  • .collapse.show 显示内容

通常,我们建议使用带有 data-bs-target 属性的 <button>。虽然从语义角度不推荐,但你也可以使用带有 href 属性的 <a> 链接(以及 role="button")。在这两种情况下,data-bs-toggle="collapse" 都是必需的。

折叠组件的一些占位内容。此面板默认隐藏,当用户激活相关触发器时会显示。
HTML
<p class="d-inline-flex gap-1">
  <a class="btn-solid theme-primary" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    使用 href 的链接
  </a>
  <button class="btn-solid theme-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    使用 data-bs-target 的按钮
  </button>
</p>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    折叠组件的一些占位内容。此面板默认隐藏,当用户激活相关触发器时会显示。
  </div>
</div>

水平方向

折叠插件支持水平折叠。添加 .collapse-horizontal 修饰符类以过渡内联尺寸而不是块尺寸,并在直接子元素上设置 width。你可以随意编写自己的自定义 Sass、使用内联样式或使用我们的宽度工具类。

请注意,虽然下面的示例设置了 min-height 以避免在我们的文档中产生过多的重绘,但这并非明确要求。只有子元素上的 width 是必需的。

这是水平折叠的一些占位内容。它默认隐藏,在触发时显示。
HTML
<p>
  <button class="btn-solid theme-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWidthExample" aria-expanded="false" aria-controls="collapseWidthExample">
    切换宽度折叠
  </button>
</p>
<div style="min-height: 140px;">
  <div class="collapse collapse-horizontal" id="collapseWidthExample">
    <div class="card card-body" style="width: 300px;">
      这是水平折叠的一些占位内容。它默认隐藏,在触发时显示。
    </div>
  </div>
</div>

多个切换和多个目标

一个 <button> 或 <a> 元素可以通过在其 data-bs-target 或 href 属性中用选择器引用多个元素,来显示和隐藏它们。 反之,多个 <button> 或 <a> 元素如果各自通过其 data-bs-target 或 href 属性引用同一个元素,则可以显示和隐藏该元素。

此多折叠示例中第一个折叠组件的一些占位内容。此面板默认隐藏,当用户激活相关触发器时会显示。
此多折叠示例中第二个折叠组件的一些占位内容。此面板默认隐藏,当用户激活相关触发器时会显示。
HTML
<p class="d-inline-flex gap-1">
  <a class="btn-solid theme-primary" data-bs-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Toggle first element</a>
  <button class="btn-solid theme-primary" type="button" data-bs-toggle="collapse" data-bs-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
  <button class="btn-solid theme-primary" type="button" data-bs-toggle="collapse" data-bs-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button>
</p>
<div class="row">
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample1">
      <div class="card card-body">
        此多折叠示例中第一个折叠组件的一些占位内容。此面板默认隐藏,当用户激活相关触发器时会显示。
      </div>
    </div>
  </div>
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample2">
      <div class="card card-body">
        此多折叠示例中第二个折叠组件的一些占位内容。此面板默认隐藏,当用户激活相关触发器时会显示。
      </div>
    </div>
  </div>
</div>

哈希链接

当 Bootstrap 在页面之后加载时,哈希链接也可使用。之后的片段更改会取消较早目标的待处理滚动。

为可折叠目标添加 data-bs-hash,以便在 URL 片段匹配其 id 时打开它。使用普通的页内链接(不带 data-bs-toggle)来尝试。如果使用粘性或固定的导航栏,你可能需要使用 scroll-margin-block-start 来进行一些视口偏移。

Open via hash link

Some placeholder content for a hash-linked collapse. Visiting #collapseHashExample opens this panel and scrolls it into view.

HTML
<p class="d-inline-flex gap-1">
  <a class="btn-outline theme-primary" href="#collapseHashExample">Open via hash link</a>
  <button class="btn-solid theme-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseHashExample" aria-expanded="false" aria-controls="collapseHashExample">
    Toggle
  </button>
</p>
<div class="collapse" id="collapseHashExample" data-bs-hash>
  <div class="card card-body">
    <p>Some placeholder content for a hash-linked collapse. Visiting <code>#collapseHashExample</code> opens this panel and scrolls it into view.</p>
  </div>
</div>

无障碍

请务必为控制元素添加 aria-expanded。该属性明确向屏幕阅读器和类似辅助技术传达与该控制关联的可折叠元素的当前状态。如果可折叠元素默认关闭,则控制元素上的属性应具有值 aria-expanded="false"。如果你已使用 show 类将可折叠元素设置为默认打开,则改为在控制元素上设置 aria-expanded="true"。插件会根据可折叠元素是否已打开或关闭自动在控制元素上切换该属性(通过 JavaScript,或因为用户触发了另一个也关联到同一可折叠元素的控制元素)。如果控制元素的 HTML 元素不是按钮(例如 <a> 或 <div>),则应为该元素添加 role="button" 属性。

折叠触发状态由 aria-expanded 表示。

如果你的控制元素定位的是单个可折叠元素——即 data-bs-target 属性指向一个 id 选择器——则应为控制元素添加 aria-controls 属性,包含可折叠元素的 id。现代屏幕阅读器和类似辅助技术利用该属性为用户提供额外的快捷方式,以直接导航到可折叠元素本身。

请注意,Bootstrap 当前的实现并不涵盖 ARIA Authoring Practices Guide accordion pattern 中描述的各种可选键盘交互——你需要使用自定义 JavaScript 自行包含这些交互。

CSS

Sass 变量

// stylelint-disable custom-property-no-missing-var-function
$collapse-tokens: defaults(
  (
    --transition-collapse-property: "block-size, display",
    --transition-collapse-duration: .35s,
    --transition-collapse-timing: ease,
  ),
  $collapse-tokens
);
// stylelint-enable custom-property-no-missing-var-function

类

折叠过渡类可以在 scss/_transitions.scss 中找到,因为它们在多个组件(折叠和手风琴)之间共享。

// The browser animates the size itself. `interpolate-size` lets the `0` of the
// closed state interpolate to the `auto` of the open one, and `display`
// transitions discretely, so the element stays laid out until the size reaches
// `0`. The animated axis is clipped, so the content cannot spill while it moves.
// Adding .collapse-instant skips all animations.
.collapse {
  @include tokens($collapse-tokens);

  overflow-y: clip;

  // Browsers without `interpolate-size` open and close the element at once.
  @media (prefers-reduced-motion: no-preference) {
    interpolate-size: allow-keywords;
  }

  &:not(.show) {
    display: none;
    block-size: 0;
  }

  // A closed collapse is not rendered, so the open side needs a start value of
  // its own. Without it the element appears at full size at once.
  &.show:not(.collapse-instant) {
    @starting-style {
      block-size: 0;
    }
  }

  // Horizontal collapses animate the inline size instead. The open size is
  // `fit-content`, so the element is as wide as its content, not as wide as its
  // container.
  &.collapse-horizontal {
    --transition-collapse-property: inline-size, display;

    inline-size: fit-content;
    overflow-x: clip;
    overflow-y: visible;

    &:not(.show) {
      inline-size: 0;
      block-size: auto;
    }

    &.show:not(.collapse-instant) {
      @starting-style {
        inline-size: 0;
      }
    }
  }
}
// Put motion in a layer so the transition-none utility can override it.
@layer components {
  .collapse:not(.collapse-instant) {
    @include transition-props(
      var(--transition-collapse-property),
      var(--transition-collapse-duration),
      var(--transition-collapse-timing),
      allow-discrete
    );
  }
}

用法

折叠插件利用两个类来处理繁重的工作:

  • .collapse 隐藏内容
  • .collapse.show 显示内容

这些类可以在 _transitions.scss 中找到。插件切换 .show,然后等待 CSS 过渡完成,再触发 shown.bs.collapse 或 hidden.bs.collapse。为可折叠元素添加 .collapse-instant 以跳过所有过渡并立即展开或折叠。

通过数据属性

只需为元素添加 data-bs-toggle="collapse" 和 data-bs-target,即可自动为一个或多个可折叠元素分配控制。data-bs-target 属性接受一个 CSS 选择器,以将折叠应用于该选择器。请务必为可折叠元素添加类 collapse。如果你希望它默认打开,请添加额外的类 show。

要为可折叠区域添加类似手风琴的组管理,请添加数据属性 data-bs-parent="#selector"。有关更多信息,请参阅手风琴页面。

属性描述
data-bs-toggle="collapse"在触发元素上初始化折叠插件。
data-bs-target要展开和折叠的元素的一个或多个 CSS 选择器。
data-bs-parent当在可折叠元素上设置时,关闭同一父元素下的同级折叠(手风琴行为)。
data-bs-hash当在可折叠目标上设置时,在 URL 片段匹配其 id 时打开该折叠(加载时以及 hashchange 时)。请参阅哈希链接。

通过 JavaScript

通过以下方式手动启用:

JavaScript
          const collapseElementList = document.querySelectorAll('.collapse')
const collapseList = [...collapseElementList].map(collapseEl => new bootstrap.Collapse(collapseEl))
        

依赖

The collapse plugin requires the following JavaScript files if you’re building Bootstrap’s JS from source:

FileDescription
js/src/collapse.tsMain collapse component
js/src/base-component.tsBase component class
js/src/dom/data.tsElement data store
js/src/dom/event-handler.tsEvent handling utilities
js/src/dom/manipulator.tsData attribute manipulation
js/src/dom/selector-engine.tsDOM selector utilities
js/src/util/config.tsConfiguration base class
js/src/util/hash-target.tsURL hash target helpers
js/src/util/index.tsCore utility functions

选项

As options can be passed via data attributes or JavaScript, you can append an option name to data-bs-, as in data-bs-animation="{value}". Make sure to change the case type of the option name from “camelCase” to “kebab-case” when passing the options via data attributes. For example, use data-bs-custom-class="beautifier" instead of data-bs-customClass="beautifier".

All components support a reserved data attribute data-bs-config that can house simple component configuration as a JSON string. When an element has data-bs-config='{"delay":0, "title":123}' and data-bs-title="456" attributes, the final title value will be 456 and the separate data attributes will override values given on data-bs-config. In addition, existing data attributes are able to house JSON values like data-bs-delay='{"show":0,"hide":150}'.

The final configuration object is the merged result of data-bs-config, data-bs-, and js object where the latest given key-value overrides the others.

名称类型默认值描述
parentselector, DOM elementnull如果提供了 parent,则当显示此可折叠项时,指定父元素下的所有可折叠元素都将被关闭。该属性必须设置在目标可折叠区域上。

方法

用于显示或隐藏组件的方法会返回一个 promise。 该 promise 在过渡结束时 resolve,因此 await 会在与 shown.bs.* 或 hidden.bs.* 监听器触发的同一时刻继续执行。这些方法仍会立即返回,绝不会阻塞调用方。对正处于过渡中的组件进行调用不会产生任何效果,并会立即 resolve。在我们的 JavaScript 文档中了解更多。

将你的内容激活为可折叠元素。接受可选的选项目 object。

构造函数会保留你的标记所声明的状态。添加 .show 以打开元素,不添加则保持元素关闭。调用 show()、hide() 或 toggle() 来更改状态。

JavaScript
          const bsCollapse = new bootstrap.Collapse('#myCollapse')
bsCollapse.show()
        
方法描述
dispose销毁元素的折叠。(移除 DOM 元素上存储的数据)
getInstance静态方法,允许你获取与 DOM 元素关联的折叠实例,你可以这样使用:bootstrap.Collapse.getInstance(element)。
getOrCreateInstance静态方法,返回与 DOM 元素关联的折叠实例,如果尚未初始化则创建一个新实例。你可以这样使用:bootstrap.Collapse.getOrCreateInstance(element)。
hide隐藏可折叠元素。返回一个 promise,在可折叠元素隐藏后 resolves(即在 hidden.bs.collapse 事件触发之后)。
show显示可折叠元素。返回一个 promise,在可折叠元素显示后 resolves(即在 shown.bs.collapse 事件触发之后)。
toggle将可折叠元素切换为显示或隐藏。返回一个 promise,在可折叠元素显示或隐藏后 resolves(即在 shown.bs.collapse 或 hidden.bs.collapse 事件触发之后)。

事件

Bootstrap 的折叠类公开了几个事件,用于挂钩折叠功能。

事件类型描述
hide.bs.collapse当调用 hide 方法时立即触发此事件。
hidden.bs.collapse当折叠元素已对用户隐藏时触发此事件(将等待 CSS 过渡完成)。
show.bs.collapse当调用 show 实例方法时立即触发此事件。
shown.bs.collapse当折叠元素已对用户可见时触发此事件(将等待 CSS 过渡完成)。
JavaScript
          const myCollapsible = document.getElementById('myCollapsible')
myCollapsible.addEventListener('hidden.bs.collapse', event => {
  // do something...
})