bootstrap 手风琴 - 点击打开的面板不会折叠

bootstrap accordion - don't collapse if clicking on open panel

我已将 bootstrap 设置为在使用以下方法打开新面板时隐藏当前打开的面板:

$('.collapse').on('show.bs.collapse', function () {
   $('.in').collapse('hide');
});

我想对此进行扩展,以便在您单击当前打开的面板时不会发生任何事情,即打开的面板在单击时应保持打开状态。它应该只在点击其他折叠面板时折叠。

我这样试过,但是不行:

$('.collapse').on('show.bs.collapse', function () {
  $('.in').not(this).collapse('hide');
});

这有可能吗?

JSFiddle

Bootstrap 添加 class 'in' 以打开面板,您可以使用它来检测面板是否已经打开,如果是这样,您可以通过调用event.stopPropagation() 您可以阅读有关 stopPropagation 的更多信息 here

$('.panel-title > a[data-toggle="collapse"]').click(function(e){
  target = $(this).attr('href')
  if ($(target).hasClass('in')) {
    e.preventDefault(); // to stop the page jump to the anchor target.
    e.stopPropagation()
  }
})

jsfiddle

根据@Sammy 的回答 - 对于 Bootstrap 4.x 你必须改变

    if ($(target).hasClass('in'))

    if ($(target).hasClass('show'))