Skip to main content Skip to docs navigation

坍塌

使用一些类和我们的 JavaScript 插件切换项目中内容的可见性。

怎么运行的

🌐 How it works

折叠 JavaScript 插件用于显示和隐藏内容。按钮或锚点用作触发器,这些触发器映射到你切换的特定元素。折叠一个元素会将 height 从当前值动画化到 0。鉴于 CSS 处理动画的方式,你不能在 .collapse 元素上使用 padding。相反,使用该类作为一个独立的封装元素。

🌐 The collapse JavaScript plugin is used to show and hide content. Buttons or anchors are used as triggers that are mapped to specific elements you toggle. Collapsing an element will animate the height from its current value to 0. Given how CSS handles animations, you cannot use padding on a .collapse element. Instead, use the class as an independent wrapping element.

The animation effect of this component is dependent on the prefers-reduced-motion media query. See the reduced motion section of our accessibility documentation.

示例

🌐 Example

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

🌐 Click the buttons below to show and hide another element via class changes:

  • .collapse 隐藏内容
  • .collapsing 在过渡期间应用
  • .collapse.show 显示内容

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

🌐 Generally, we recommend using a <button> with the data-bs-target attribute. While not recommended from a semantic point of view, you can also use an <a> link with the href attribute (and a role="button"). In both cases, the data-bs-toggle="collapse" is required.

Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger.
html
<p class="d-inline-flex gap-1">
  <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    Link with href
  </a>
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Button with data-bs-target
  </button>
</p>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger.
  </div>
</div>

水平的

🌐 Horizontal

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

🌐 The collapse plugin supports horizontal collapsing. Add the .collapse-horizontal modifier class to transition the width instead of height and set a width on the immediate child element. Feel free to write your own custom Sass, use inline styles, or use our width utilities.

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

This is some placeholder content for a horizontal collapse. It’s hidden by default and shown when triggered.
html
<p>
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseWidthExample" aria-expanded="false" aria-controls="collapseWidthExample">
    Toggle width collapse
  </button>
</p>
<div style="min-height: 120px;">
  <div class="collapse collapse-horizontal" id="collapseWidthExample">
    <div class="card card-body" style="width: 300px;">
      This is some placeholder content for a horizontal collapse. It’s hidden by default and shown when triggered.
    </div>
  </div>
</div>

多个切换和目标

🌐 Multiple toggles and targets

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

🌐 A <button> or <a> element can show and hide multiple elements by referencing them with a selector in its data-bs-target or href attribute. Conversely, multiple <button> or <a> elements can show and hide the same element if they each reference it with their data-bs-target or href attribute.

Some placeholder content for the first collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
Some placeholder content for the second collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
html
<p class="d-inline-flex gap-1">
  <a class="btn btn-primary" data-bs-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Toggle first element</a>
  <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
  <button class="btn btn-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">
        Some placeholder content for the first collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
      </div>
    </div>
  </div>
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample2">
      <div class="card card-body">
        Some placeholder content for the second collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
      </div>
    </div>
  </div>
</div>

无障碍

🌐 Accessibility

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

🌐 Be sure to add aria-expanded to the control element. This attribute explicitly conveys the current state of the collapsible element tied to the control to screen readers and similar assistive technologies. If the collapsible element is closed by default, the attribute on the control element should have a value of aria-expanded="false". If you’ve set the collapsible element to be open by default using the show class, set aria-expanded="true" on the control instead. The plugin will automatically toggle this attribute on the control based on whether or not the collapsible element has been opened or closed (via JavaScript, or because the user triggered another control element also tied to the same collapsible element). If the control element’s HTML element is not a button (e.g., an <a> or <div>), the attribute role="button" should be added to the element.

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

🌐 If your control element is targeting a single collapsible element – i.e. the data-bs-target attribute is pointing to an id selector – you should add the aria-controls attribute to the control element, containing the id of the collapsible element. Modern screen readers and similar assistive technologies make use of this attribute to provide users with additional shortcuts to navigate directly to the collapsible element itself.

请注意,Bootstrap 当前的实现并未涵盖 ARIA 编写实践指南手风琴模式 中描述的各种可选键盘交互——你需要使用自定义 JavaScript 自行添加这些功能。

🌐 Note that Bootstrap’s current implementation does not cover the various optional keyboard interactions described in the ARIA Authoring Practices Guide accordion pattern - you will need to include these yourself with custom JavaScript.

CSS

Sass 变量

🌐 Sass variables

$transition-collapse:         height .35s ease;
$transition-collapse-width:   width .35s ease;

🌐 Classes

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

🌐 Collapse transition classes can be found in scss/_transitions.scss as these are shared across multiple components (collapse and accordion).

.collapse {
  &:not(.show) {
    display: none;
  }
}

.collapsing {
  height: 0;
  overflow: hidden;
  @include transition($transition-collapse);

  &.collapse-horizontal {
    width: 0;
    height: auto;
    @include transition($transition-collapse-width);
  }
}

用法

🌐 Usage

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

🌐 The collapse plugin utilizes a few classes to handle the heavy lifting:

  • .collapse 隐藏内容
  • .collapse.show 显示内容
  • 当过渡开始时会添加 .collapsing,当过渡结束时会移除

这些类可以在 _transitions.scss 中找到。

🌐 These classes can be found in _transitions.scss.

通过数据属性

🌐 Via data attributes

只需向元素添加 data-bs-toggle="collapse"data-bs-target,即可自动分配一个或多个可折叠元素的控制权。data-bs-target 属性接受一个 CSS 选择器以应用折叠。请确保向可折叠元素添加类 collapse。如果你希望其默认展开,请添加额外的类 show

🌐 Just add data-bs-toggle="collapse" and a data-bs-target to the element to automatically assign control of one or more collapsible elements. The data-bs-target attribute accepts a CSS selector to apply the collapse to. Be sure to add the class collapse to the collapsible element. If you’d like it to default open, add the additional class show.

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

🌐 To add accordion-like group management to a collapsible area, add the data attribute data-bs-parent="#selector". Refer to the accordion page for more information.

通过 JavaScript

🌐 Via JavaScript

手动启用:

🌐 Enable manually with:

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

选项

🌐 Options

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".

As of Bootstrap 5.2.0, all components support an experimental 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.

名称类型默认值描述
parent选择器,DOM 元素null如果提供了父元素,则在显示此可折叠项时,指定父元素下的所有可折叠元素将被关闭。(类似传统手风琴行为——这取决于 card 类)。该属性必须设置在目标可折叠区域上。
toggle布尔值true调用时切换可折叠元素的状态。

方法

🌐 Methods

All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started, but before it ends. In addition, a method call on a transitioning component will be ignored. Learn more in our JavaScript docs.

将你的内容激活为可折叠元素。可选择接受可选参数 object

🌐 Activates your content as a collapsible element. Accepts an optional options object.

你可以使用构造函数创建折叠实例,例如:

🌐 You can create a collapse instance with the constructor, for example:

const bsCollapse = new bootstrap.Collapse('#myCollapse', {
  toggle: false
})
方法描述
dispose销毁元素的折叠。 (移除DOM元素上存储的数据)
getInstance静态方法,允许你获取与DOM元素关联的折叠实例,你可以这样使用它:bootstrap.Collapse.getInstance(element)
getOrCreateInstance静态方法,返回与DOM元素关联的折叠实例,如果未初始化则创建一个新的实例。你可以这样使用它:bootstrap.Collapse.getOrCreateInstance(element)
hide隐藏可折叠元素。在可折叠元素真正被隐藏之前就返回给调用者(例如,在 hidden.bs.collapse 事件发生之前)。
show显示可折叠元素。在可折叠元素真正被显示之前就返回给调用者(例如,在 shown.bs.collapse 事件发生之前)。
toggle切换可折叠元素的显示或隐藏状态。在可折叠元素真正被显示或隐藏之前就返回给调用者(即在 shown.bs.collapsehidden.bs.collapse 事件发生之前)。

事件

🌐 Events

Bootstrap 的 collapse 类公开了一些用于挂载 collapse 功能的事件。

🌐 Bootstrap’s collapse class exposes a few events for hooking into collapse functionality.

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