Bootstrap 4: switch between cols on mobile

折月煮酒 提交于 2019-12-12 11:34:44

问题


I've built a standard layout with a sidebar using Bootstrap's grid system (EDIT: I'm using Bootstrap 4 but could still switch). It looks like this:

<div class="row">
  <div class="col-md-3">
    ...
  </div>
  <div class="col-md-9">
    <div class="row">
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
    </div>
  </div>
</div>

On mobile, the red area would be above the green one. I need to be able to switch between them in a way that is more convenient than scrolling, for example a switch button:

Also note the different oder of elements in the green area.

Is there a smart way to do this? Or do I have to alter the dom with JavaScript? Thanks in advance :)


回答1:


You can use jQuery to toggle one of the BS4 flexbox utility classes. For example, apply the flex-last on the first (col-md-3) column.

To switch the order on mobile using a button, toggle the flex-last class...

$('#btnToggle').click(function(){
    $('.col-md-3').toggleClass('flex-last');
})

EDIT: To show only one at a time (switch the visibility of the 2 divs using a button) toggle the hidden-sm-down class instead...

$('#btnToggle').click(function(){
    $('.col-md-3, .col-md-9').toggleClass('hidden-sm-down');
})

Demo


In Bootstrap 4, column order can be toggled using CSS only, but this switches the cols based on screen width, and therefore is not triggered by the button.

<div class="row">
  <div class="col-md-3 flex-last flex-md-unordered">
    ...
  </div>
  <div class="col-md-9">
    <div class="row">
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
    </div>
  </div>
</div>

Update

As of Bootstrap 4 Beta 3, the ordering classes are named order-*, such as order-1, order-md-2, etc..




回答2:


Bootstrap 4 uses Flexbox, which means you could utilise the order in which things are displayed.

As usual, you can specify how it's displayed on different viewports using classes like order-last and order-sm-unordered.

flexbox/order documentation



来源:https://stackoverflow.com/questions/43092328/bootstrap-4-switch-between-cols-on-mobile

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