You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Bootstrap 5 collapse折叠组件每次仅展开一个元素的效果

解决方案

Bootstrap 5的折叠组件原生支持互斥展开效果,不需要额外编写JavaScript代码,只需要做两处简单修改即可:

  • 给所有折叠项的外层添加一个带唯一ID的父容器,这里我们统一用id="collapseGroup"作为父容器标识
  • 给每个.collapse元素添加data-bs-parent属性,属性值指向刚才定义的父容器ID,即data-bs-parent="#collapseGroup"

修改后的完整代码如下:

<!-- 新增外层父容器 -->
<div id="collapseGroup">
  <p>
    <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>
  </p>
  <div class="row">
    <div class="col">
      <!-- 给collapse元素加data-bs-parent属性 -->
      <div class="collapse multi-collapse" id="multiCollapseExample1" data-bs-parent="#collapseGroup">
        <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">
      <!-- 给第二个collapse元素也加data-bs-parent属性 -->
      <div class="collapse multi-collapse" id="multiCollapseExample2" data-bs-parent="#collapseGroup">
        <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>
</div>

修改完成后,点击任意按钮展开对应折叠项时,其他已展开的折叠项会自动收起,完全符合你需要的手风琴交互效果。

内容的提问来源于stack exchange,提问作者jchillaxin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 02:39:00