Bootstrap 3 collapse can have multiple panels open after programmatically opening a panel

江枫思渺然 提交于 2019-11-29 03:17:40

You can create a handler for the collapse show event which occurs just before any panels are displayed.

Add this to ensure any other open panels are closed before the selected one is shown:

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

Bootply demo

You can read more about the collapse events here: http://getbootstrap.com/javascript/#collapse

I think the problem is due to the way you are changing the open panel. Rather than using the 'show' feature you need to fire the click event on the appropriate panel link. For example with an accordion with an id "accordion", with three panels, if you want to show the 2 panel then use:

$("a[href=#accordion-2]").click()

Or whatever ID you have given your second panel (I use twitterboostrapmvc so the panel ids are auto-generated from the accordion ID).

For anyone using data-target attributes to control the accordion (rather than the href attribute), this is an adaptation of ProfNimrod's answer which will click the relevant element if the target is currently hidden. (Note that the if check relies on setting up the accordion with the collapsed class applied by default, which I find useful anyway to take advantage of using css to put a chevron icon on the accordions).

var expandAccordion = function() {
    var header = $('[data-target="#accordion-0"]');
    if (header.hasClass('collapsed')) {
        header.click();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!