Bootstrap data-toggle collapses div after second click, not first

天大地大妈咪最大 提交于 2019-12-23 09:45:40

问题


I have the simple example with Bootstrap and toggling divs by click. Here is markup:

<div class="accordion-heading">
    <a class="accordion-toggle"
       data-toggle="collapse"
       data-parent="#accordion2"
       href="#collapseOne">Open!</a>
</div>
<div id="collapseOne" class="accordion-body">
    <div class="span6">
        <div class="well well-small">
            <div class="accordion-toggle">
                ...some text...
            </div>
        </div>
    </div>
    <div class="span2"></div>                            
</div>

When user clixks link with title 'Open!' underlying div expands or collapses. Div is expanded initially and when user clicks first time it has no effect. Then if user clicks second time, div collapses.

In the original example div is collapsed initially but I would like it to be opened. How could I fix the problem?


回答1:


Just add class 'collaspe in' to class="accordion-body".

Check example code at CODEPEN

HTML:

<div class="accordion-heading">
    <a class="accordion-toggle"
       data-toggle="collapse"
       data-parent="#accordion2"
       href="#collapseOne">Open!</a>
</div>
<div id="collapseOne" class="accordion-body collapse in">
    <div class="span6">
        <div class="well well-small">
            <div class="accordion-toggle">
                ...some text...
            </div>
        </div>
    </div>
    <div class="span2"></div>                            
</div>

I hope this will fix your issue. Enjoy :)




回答2:


<div id="collapseOne" class="accordion-body collapse">

This will also make it close by default and open when clicked




回答3:


<a class="btn btn-primary" data-toggle="collapse" href="#collapsePanel" role="button" aria-expanded="false" aria-controls="collapsePanel">Collapse</a>

<div id="collapsePanel" class="collapse show"><!-- Content Here --></div>

This will make it collapsible, but show the panel by default. When you click the Collapse button, it will collapse the panel on the first click.

I'm only adding this here for if anyone is looking to do it either way. I found this link when searching for its inverse. Hope it helps!




回答4:


You should be calling bootstrap.min.js twice. Make sure that you're calling bootstrap files only once. If you're using Bootstrap with Laravel or any kind of framework, keep in mind that npm run dev compiles bootstrap js files in app.js. That could be the case.



来源:https://stackoverflow.com/questions/39290431/bootstrap-data-toggle-collapses-div-after-second-click-not-first

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