移动端默认折叠表格DIV,桌面端正常显示表格的实现需求
Got it, let's sort out this responsive table collapse requirement for you! Here's a straightforward solution that works exactly as you need:
Step 1: Control the Toggle Button Visibility
First, we only want the collapse button to show on mobile. Bootstrap's responsive display classes make this easy—add d-md-none to the button. This hides the button on screens 768px and wider (desktop) and shows it on smaller mobile screens.
<a class="btn btn-primary d-md-none" data-toggle="collapse" href="#table-collapse" role="button" aria-expanded="false" aria-controls="table-collapse"> Toggle Table </a>
Step 2: Set Up the Table for Responsive Collapse
Add the collapse class to your table so it starts collapsed by default (perfect for mobile). Then, we'll use a CSS media query to force it to display normally on desktop.
<table class="table table-borderless collapse" id="table-collapse"> <tbody> <tr> <td>Name</td> <td>City</td> <td>Country</td> </tr> <tr> <td>John Doe</td> <td>New York</td> <td>USA</td> </tr> <!-- Add more rows as needed --> </tbody> </table>
Step 3: Force Table to Show on Desktop
Add this CSS snippet to override the collapse behavior on desktop screens. The !important ensures it takes precedence over Bootstrap's collapse styles:
/* Desktop screens (768px and wider) */ @media (min-width: 768px) { #table-collapse { display: table !important; } }
Full Working Example
Here's the complete code you can drop in and test:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"> <style> @media (min-width: 768px) { #table-collapse { display: table !important; } } </style> </head> <body> <a class="btn btn-primary d-md-none" data-toggle="collapse" href="#table-collapse" role="button" aria-expanded="false" aria-controls="table-collapse"> Toggle Table </a> <table class="table table-borderless collapse" id="table-collapse"> <tbody> <tr> <td>Name</td> <td>City</td> <td>Country</td> </tr> <tr> <td>John Doe</td> <td>New York</td> <td>USA</td> </tr> <tr> <td>Jane Smith</td> <td>London</td> <td>UK</td> </tr> </tbody> </table> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
How It Works
- Mobile: The button is visible, and the table starts collapsed. Users can tap the button to expand/collapse it.
- Desktop: The button is hidden, and the CSS forces the table to display as a normal table—no collapse behavior at all.
内容的提问来源于stack exchange,提问作者ikt

