Bootstrap 3 collapsible panel without id or data

╄→гoц情女王★ 提交于 2021-01-28 19:40:32

问题


I need to handle panel collapse behavior without using ID or data attributes. Ideally by setting a "collapsible" class on the parent div that can collapse its content, and a click on the heading should trigger the collapse

Here's the target HTML I'd like to write to handle collapse behavior automatically

<div class="panel-group collapse-all-but-one">
    <div class="panel panel-primary panel-collapsible>
        <div class="panel-heading">Click me to collapse</div>
        <div class="panel-body">I will collaaaaaaapse</div>
    </div>
    <div class="panel panel-warning panel-collapsible">
        <div class="panel-heading">Hey another one</div>
        <div class="panel-body">I will close when the other one opens</div>
    </div>
</div>

回答1:


Here's my magic piece of code (the ready stuff ensures compatibility with rails/angularJS)

var ready
ready = function(){
    $(".panel-collapsable")
    .children(".panel-heading")
        .click(function(){
            var group = $(this).parent().parent()
            if (group.hasClass("panel-group one-at-a-time")){
                group.children(".panel").children(".panel-body")
                    .collapse('hide')
            }
            $(this)
                .next('.panel-body')
                .collapse('toggle')
        })
}
$(document).ready(ready);
$(document).on('page:load', ready);

Remember to add some bootstrap classes like .collapse .in or .collapsed to initialize correct behaviour or the first click isn't going to do anything.

<div class="panel-body collapse in">I am expanded on page load</div>
...
<div class="panel-body collapse">I am collapsed on page load</div>


来源:https://stackoverflow.com/questions/25525122/bootstrap-3-collapsible-panel-without-id-or-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!