Bootstrap 4 Collapse Accordion - always have one panel open

前端 未结 2 1889
长情又很酷
长情又很酷 2020-12-18 05:57

I\'m using Bootstrap 4.0\'s collapse component in an accordion similar to what they have on their docs.

相关标签:
2条回答
  • 2020-12-18 06:53

    You can use the collapse hidden event. In this case, use .eq(0) since 0 is the index of the first collapsible div.

    $('.collapse').on('hidden.bs.collapse', function () {
        $('.collapse').eq(0).collapse('show');
    })
    

    To take it a step further, you could add a new default data variable to the parent #accordion...

    <div id="accordion" class="accordion" data-default="1">..</div>

    And, then change the jQuery to use that variable..

    /* default accordion variable method */
    $('.collapse').on('hidden.bs.collapse', function () {
      var defaultDiv = $($(this).data("parent")).data("default");
      $('.collapse').eq(defaultDiv-1).collapse('show');
    })
    

    Demo: https://www.codeply.com/go/NilPIQD9oi


    Another option is to prevent any open accordion from closing itself, as I explained in this answer.

    0 讨论(0)
  • 2020-12-18 06:55

    You can try

    jQuery(function($){
        $('[data-toggle=collapse]').on('click', function (e) {
            e.preventDefault();
            if(! $(this).hasClass('collapsed')){
                e.stopPropagation();
                return false;
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题