简体   繁体   English

单击时关闭活动的 Bootstrap 5 选项卡

[英]Close active Bootstrap 5 Tab on click

This question has been asked for Bootstrap 4 and lower but not for Bootstrap 5 I think.这个问题已被问到 Bootstrap 4 及更低版本,但我认为不是 Bootstrap 5。 For Bootstrap 4 I used some Jquery like this https://www.codeply.com/go/bp/61835对于 Bootstrap 4,我使用了一些像这样的 Jquery https://www.codeply.com/go/bp/61835

When an active tab gets clicked, the 'active' class should be removed from the tab button and the tab pane should be hidden.单击活动选项卡时,应从选项卡按钮中删除“活动”类,并隐藏选项卡窗格。

Does someone has a simple solution for that?有人有一个简单的解决方案吗? I cannot get it to work without calling preventDefault() for the Bootstrap events ('show', etc) and doing everything manually.如果不为 Bootstrap 事件(“显示”等)调用 preventDefault() 并手动执行所有操作,我将无法使其工作。

Thanks!谢谢!

There's a good example of how to use tabs on the Bootstrap website here .这里有一个很好的例子来说明如何在Bootstrap 网站上使用选项卡。

There is still an active class which sits on the trigger eg <button> and the target (which also uses the show class), but the JS has more emphasis on control through data attributes in combination with aria (eg aria-selected="true" ):仍然有一个active类位于触发器上,例如<button>和目标(也使用show类),但 JS 更强调通过数据属性结合 aria 进行控制(例如aria-selected="true" ):

<button class="nav-link active" id="pills-home-tab" data-bs-toggle="pill" data-bs-target="#pills-home" type="button" role="tab" aria-controls="pills-home" aria-selected="true">Home</button>

... 

<div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab" tabindex="0">...</div>

If you also scroll further down on the Bootstrap link above, there is a bit dedicated to JS control.如果您还在上面的 Bootstrap 链接上进一步向下滚动,则有一些专门用于 JS 控制。 eg例如

Enable tabbable tabs via JavaScript (each tab needs to be activated individually):通过 JavaScript 启用可选项卡(每个选项卡需要单独激活):

const triggerTabList = document.querySelectorAll('#myTab button')
triggerTabList.forEach(triggerEl => {
  const tabTrigger = new bootstrap.Tab(triggerEl)

  triggerEl.addEventListener('click', event => {
    event.preventDefault()
    tabTrigger.show()
  })
})

You can activate individual tabs in several ways:您可以通过多种方式激活单个选项卡:

const triggerEl = document.querySelector('#myTab button[data-bs-target="#profile"]')
bootstrap.Tab.getInstance(triggerEl).show() // Select tab by name

const triggerFirstTabEl = document.querySelector('#myTab li:first-child button')
bootstrap.Tab.getInstance(triggerFirstTabEl).show() // Select first tab

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM