简体   繁体   中英

How do I combine pills, collapse and tabs in bootstrap?

I am trying to create some pills, which when clicked will show and switch between some content.

This works fine.

I would like to hide the content as well, when clicking the active pill again. This I cannot get to work.

This is my current code, which you can try at this fiddle: https://jsfiddle.net/9phcsmwa/1/

When you click one of the pills it will display the content, and when you click another pill it will switch between the content like tabs. But how do I hide the content, when clicking on the active pill?

<div id="accordion">
    <div data-parent="#accordion" href="">
        <ul id="tabs" class="nav nav-pills" data-toggle="collapse" data-tabs="tabs">
            <li><a data-toggle="tab" href="#Pill1" class="btn btn-s-md btn-white m-b">Pill1</a></li>
            <li><a data-toggle="tab" href="#Pill2" class="btn btn-s-md btn-white m-b">Pill2</a></li>
            <li><a data-toggle="tab" href="#Pill3" class="btn btn-s-md btn-white m-b">Pill2</a></li>
        </ul>
    </div>
</div>

<div id="collapse" class="panel-collapse collapse in">
    <div class="tab-content">
        <div id="Pill1" class="tab-pane fade">
            <h3>Pill 1</h3>
            <p>Some content.</p>
        </div>
        <div id="Pill2" class="tab-pane fade">
            <h3>Pill 2</h3>
            <p>Some content for Pill 2.</p>
        </div>
        <div id="Pill3" class="tab-pane fade">
            <h3>Pill 3</h3>
            <p>Some content for Pill 3.</p>
        </div>
    </div>
</div>    

Thanks.

You do not need javascript for this, you just need to change all of your references to tabs to collapse. Tabs are meant for one to always be shown, however, collapse is made to ... collapse!

Here is you JSFiddle Updated

Changes include:

  • All of your data-toggle="tab" are now data-toggle="collapse" .
  • All of your class="tab-pane fade" are now class="collapse fade" .
  • Wrapped your three tab contents in a panel. This is due to a bug with data-parent in Bootstrap. Details can be found here .
  • Removed data-parent="#accordion" and then added data-parent="#collapse" to all three of your Pills.

You can add this jQuery code :

$(document).ready(function() {
    $('#accordion [data-toggle="tab"]').click(function() {
       var $targetTabContent = $($(this).attr('href'));
       if ($targetTabContent.hasClass('active')) {
          $targetTabContent.removeClass('active');
       }    
    });
});

Updated JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM