Switch from tabs to collapse for responsive

2020-07-09 10:30发布

问题:

The goal is to switch from tabs to an accordion style collapse when the site is less than 676px wide. We are using Bootstrap.

We'll hide ul.nav-tabs and a.accordtion-toggle respectively with css. The tabs work here, but the a.accordion-toggle aren't working. Any ideas?

<ul class="nav nav-tabs" id="myTab" data-tabs="tabs">
  <li class="active"><a href="#panel1" data-toggle="tab">Panel 1</a></li>    
  <li class="active"><a href="#panel2" data-toggle="tab">Panel 2</a></li> 
</ul>

<a class="accordion-toggle" data-toggle="collapse" data-target="#panel>Panel 1</a>
  <div class="tab-pane collapse" id="panel1">
 Panel 1 Content
  </div>
<a class="accordion-toggle" data-toggle="collapse" data-target="#pane2>Panel 2</a>
  <div class="tab-pane collapse" id="panel2">
 Panel 2 Content
  </div>

<script>
  jQuery(document).ready(function ($) {
    if (document.documentElement.clientWidth <  767) {
        $('#myTab a').click(function (e) {
          e.preventDefault();
        }

        $(".collapse").collapse();
     }              
  });
</script>

回答1:

I tried a bit on this jsfiddle but it seems complicated to make both plugins work together.

It might be better opting for one of the plugin, using only the classes and JS of this plugin, and then implement your own triggers to complete the default behavior.


I think the accordion behavior of the collapse plugin needs the .accordion-group > .collapse.in structure to work properly - if you don't use your own JS.



回答2:

In my case just copying tabs content into hidden accordion worked well.

Here is the source I extracted to small plugin - Bootstrap Tab Collapse



回答3:

I ended up nesting the tab triggers inside one div with the tabbed content (instead of a list above) and using css to position them like tabs for the full screen view. Not ideal but works as long as the data-toggle and data-target are in place.



回答4:

Not sure if it helps but you could use window.onresize = function() {} and check for the width of your main container. When it is less than some width you could replace the content using js.