twitter-bootstrap 你如何让 Twitter Bootstrap Accordion 保持一组开放?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15725717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 16:47:34  来源:igfitidea点击:

How do you make Twitter Bootstrap Accordion keep one group open?

twitter-bootstrapaccordiontwitter-bootstrap-3

提问by Archimedes Trajano

I am trying to mimic the Outlook bar using Twitter bootstrap using the accordion and collapse plugin, so far I got the collapse and accordion working, but it presently allows for all sections to be collapsed.

我正在尝试使用手风琴和折叠插件使用 Twitter 引导程序模拟 Outlook 栏,到目前为止,我的折叠和手风琴工作正常,但它目前允许折叠所有部分。

I would like to limit it so that one and only one is always shown.

我想限制它,以便始终只显示一个。

Here is the one I am working on: http://jsfiddle.net/trajano/SMT9D/and I think it's somewhere along the lines of

这是我正在研究的一个:http: //jsfiddle.net/trajano/SMT9D/,我认为它在某个地方

$('#accordions').on('hide', function (event) {
  console.warn("HIDE TRIGGERED, check if trying to hide the active one if so stop");
})

回答by Hugo Dozois

Here is an easy way to do it:

这是一个简单的方法:

New Bootstrap 3

新引导程序 3

JsFiddlefor Bootstrap 3.

用于 Bootstrap 3 的JsFiddle

Code for Bootstrap 3:

Bootstrap 3 的代码:

$('.panel-heading a').on('click',function(e){
    if($(this).parents('.panel').children('.panel-collapse').hasClass('in')){
        e.stopPropagation();
    }
    // You can also add preventDefault to remove the anchor behavior that makes
    // the page jump
    // e.preventDefault();
});

The code checks if the clicked element is the one that is currently shown (by the class "in")and if it does have the "in" class, it stops the hiding process.

代码检查被点击的元素是否是当前显示的元素(通过“in”类),如果它确实有“in”类,它会停止隐藏过程。



Deprecated Bootstrap 2

弃用的 Bootstrap 2

JsFiddlefor Bootstrap 2.

用于 Bootstrap 2 的JsFiddle

Code for Bootstrap 2:

Bootstrap 2 的代码:

$('.accordion-toggle').on('click',function(e){
    if($(this).parents('.accordion-group').children('.accordion-body').hasClass('in')){
        e.stopPropagation();
    }
    // You can also add preventDefault to remove the anchor behavior that makes
    // the page jump
    // e.preventDefault();
});


Note:Be careful if you want to attach more click events on the accordion, since the e.stopPropagation()will block events that would occur after the check.

注意:如果你想在手风琴上附加更多的点击事件,请小心,因为这e.stopPropagation()会阻止检查后发生的事件。

回答by Aelios

I want to precise @Hugo Dozois 's answer

我想精确@Hugo Dozois 的回答

http://jsfiddle.net/SMT9D/61/

http://jsfiddle.net/SMT9D/61/

You should add e.preventDefault();to prevent the default behaviour of #HTML anchor if you have a scroll in your page

如果页面中有滚动,则应添加e.preventDefault();以防止#HTML 锚点的默认行为

$('.panel-heading a').on('click',function(e){
    if($(this).parents('.panel').children('.panel-collapse').hasClass('in')){
        e.preventDefault();
        e.stopPropagation();
    }
});

回答by Zim

Updated 2018

2018 年更新

Here's how to keep at least open in both Bootstrap v3 or v4. This means that the open accordion can onlybe closed by toggling another one open.

以下是如何在 Bootstrap v3 或 v4 中至少保持打开状态。这意味着打开的手风琴只能通过打开另一个手风琴来关闭

Bootstrap 4

引导程序 4

https://www.codeply.com/go/bbCcnl0jBB

https://www.codeply.com/go/bbCcnl0jBB

// the current open accordion will not be able to close itself
$('[data-toggle="collapse"]').on('click',function(e){
    if ( $(this).parents('.accordion').find('.collapse.show') ){
        var idx = $(this).index('[data-toggle="collapse"]');
        if (idx == $('.collapse.show').index('.collapse')) {
            e.stopPropagation();
        }
    }
});

Also, see this answerwhich shows how to specify a "default" accordion that will open when all others are closed.

此外,请参阅此答案,其中显示了如何指定在所有其他手风琴关闭时将打开的“默认”手风琴。



Bootstrap 3

引导程序 3

$('[data-toggle="collapse"]').on('click',function(e){
    if($(this).parents('.panel').find('.collapse').hasClass('in')){
        var idx = $(this).index('[data-toggle="collapse"]');
        var idxShown = $('.collapse.in').index('.accordion-body');
        if (idx==idxShown) {
            e.stopPropagation();
        }
    }
});

https://www.codeply.com/go/yLw944BrgA

https://www.codeply.com/go/yLw944BrgA

<div class="accordion" id="myAccordion">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
        <div id="collapsible-1" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
        <div id="collapsible-2" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
        <div id="collapsible-3" class="collapse">
           ...
        </div>
    </div>
</div>

(Note:the panelclass is needed in Bootstrap 3 to make the accordion behavior work)

注:panel需要自举3类,以使手风琴行为的工作

回答by Heri Hehe Setiawan

Or you can use simple CSS trick as follows:

或者您可以使用简单的 CSS 技巧,如下所示:

/*
prevent the active panel from collapsing
 */
.panel-group [aria-expanded=true]{
  /*
  http://caniuse.com/#feat=pointer-events
  Works for MOST modern browsers. (- Opera Mobile)
  */
  pointer-events: none;
}

must have proper tags on the inactive panel links

非活动面板链接上必须有适当的标签

 aria-expanded="false"

回答by chris

As all the other JS answers use an inadvisablestopPropagation()here is my solution using just the native Bootstrap events (tested on Bootstrap 4).

由于所有其他 JS 答案都使用了不可取的stopPropagation(),因此我的解决方案仅使用本机 Bootstrap 事件(在 Bootstrap 4 上测试)。

JsFiddle

JsFiddle

$('#accordionExample').on('show.bs.collapse', function () {
    $(this).data('isShowing', true);
});

$('#accordionExample').on('hide.bs.collapse', function (event) {
    if (!$(this).data('isShowing')) {
        event.preventDefault();
    }

    $(this).data('isShowing', false);
});

It makes use of the fact that a click on a collapsed element will result in a show.bs.collapsefollowed by a hide.bs.collapse. Whereas a click on the open element will result in just a hide.bs.collapse.

它利用了这样一个事实,即单击折叠的元素将导致 ashow.bs.collapse后跟 a hide.bs.collapse。而单击打开的元素只会产生一个hide.bs.collapse.

回答by kpull1

I have a scenario that do not fit with any posted answer: multiple accordions on the same page and some other collapsible components that are not accordions (without data-parentattribute).

我有一个不适合任何已发布答案的场景:同一页面上的多个手风琴和其他一些不是手风琴的可折叠组件(无data-parent属性)。

$("[data-toggle=collapse][data-parent]").click(function (e) {
    var button = $(this);
    var parent = $(button.attr("data-parent"));
    var panel = parent.find(button.attr("href") || button.attr("data-target"));
    if (panel.hasClass("in")) {
        e.preventDefault();
        e.stopPropagation()
    }
});

This code only triggers on accordions, since checks data-parentattribute. It also does not assume a card(or panelfor bootstrap 3) structure, it uses the same attributes that bootstrap api.

此代码仅在手风琴上触发,因为检查data-parent属性。它也不假设一个card(或panel对于 bootstrap 3)结构,它使用与 bootstrap api 相同的属性。

I hope it helps.

我希望它有帮助。

回答by Johannes Filter

Bootstrap 4.0

引导程序 4.0

$('.card').click(function(e) {
  if (
    $(this)
      .find('.collapse')
      .hasClass('show')
  ) {
    e.stopPropagation();
  }
});

This code block checks if the clicked card is collapsed (by looking at the div with the class collapse). When the card is currently shown it stops propagating the event.

此代码块检查单击的卡片是否折叠(通过查看带有 class 的 div collapse)。当卡片当前为shown 时,它停止传播事件

回答by shalini

As per bootstarp 3.3.6 version , just follow structure

根据 bootstarp 3.3.6 版本,只需遵循结构

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<div class="panel-group" id="accordion" role="tablist"   aria-multiselectable="true">

  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingOne">
      <h4 class="panel-title">
        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
      <div class="panel-body">
        collopse 1 body  here 
      </div>
    </div>
  </div>

  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingTwo">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
      <div class="panel-body">
        collapse body 2
      </div>
    </div>
  </div>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>