使用Bootstrap点击按钮切换div时多div同时显示问题咨询
问题原因
- 重复ID:HTML要求DOM元素id必须全局唯一,你的代码中按月、按年计费分别对应了两个相同id的div,会导致Bootstrap折叠选择器识别异常
- 缺少互斥折叠配置:Bootstrap默认collapse组件是独立切换的,要实现点击一个自动隐藏其他折叠项的效果,需要使用手风琴(accordion)的父容器关联配置
修正方案
- 把所有折叠内容统一放到同一个父容器下,给父容器设置唯一id作为手风琴容器
- 把同类型的折叠内容合并到同一个id的容器内,避免重复id
- 给两个切换按钮添加
data-bs-parent属性,指向手风琴父容器的id,实现互斥切换
修正后完整代码
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="row justify-content-evenly"> <div class="col d-grid gap-2 col-3 mt-4 mb-3"> <button type="button" class="btn btn-outline-primary" id="billed-monthly" value="monthly" style="border: solid 1px grey;" data-bs-toggle="collapse" data-bs-target="#billmonthly" data-bs-parent="#billingCollapse" aria-expanded="false" aria-controls="billmonthly">Billed Monthly</button> </div> <div class="col d-grid gap-2 col-3 mt-4 mb-3"> <button type="button" class="btn btn-outline-primary" id="billed-yearly" value="yearly" style="border: solid 1px grey;" data-bs-toggle="collapse" data-bs-target="#billyearly" data-bs-parent="#billingCollapse" aria-expanded="false" aria-controls="billyearly">Billed Yearly</button> </div> </div> <!-- 手风琴父容器 --> <div id="billingCollapse" class="accordion"> <!-- 按月计费内容合并为一个容器,id唯一 --> <div class="row mt-2 collapse" id="billmonthly"> <div class=" col d-flex justify-content-end"> <div> <h3>Billed now: 199</h3> <p>By clicking "Start Premium Plan", you agree to be charge 199 every<br> month, unless you cancel. You acknowledge that refunds won't be<br> available on cancellation.</p> </div> </div> </div> <!-- 按年计费内容合并为一个容器,id唯一 --> <div class="row mt-2 collapse" id="billyearly"> <div class=" col d-flex justify-content-end"> <div> <h3>Billed now: 2030</h3> <p>By clicking "Start Premium Plan", you agree to be charge 2030 every<br> year, unless you cancel. You acknowledge that refunds won't be<br> available on cancellation.</p> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
可选方案(不合并内容结构)
如果你不想调整现有内容结构,也可以用类选择器代替id选择器实现多个元素同时切换,修改方式如下:
- 给两个按月计费的div去掉重复id,添加统一class:
billmonthly - 给两个按年计费的div去掉重复id,添加统一class:
billyearly - 按钮的
data-bs-target属性对应改为.billmonthly和.billyearly - 依旧保留
data-bs-parent属性关联父容器实现互斥
内容的提问来源于stack exchange,提问作者Niteesh kulhari
相关产品推荐
相关产品推荐

