如何实现移动端和平板端可滚动的响应式Bootstrap DataTable
解决Bootstrap DataTable移动端/平板端无法横向滚动的问题
问题说明
开发包含Bootstrap DataTable的响应式页面时,移动端和平板端无法滚动表格查看完整表头及对应数据,需要在保留搜索栏、分页功能的同时实现表格横向滚动。
修复方案
- 移除固定宽度限制:原CSS中给
dataTables_wrapper设置的固定800px宽度会限制容器自适应能力,需调整为自适应宽度并添加滚动容器样式。 - 调整DataTable配置:关闭默认的
responsive: true(该模式会折叠列而非提供滚动),改用scrollX: true开启横向滚动,同时保留FixedHeader功能。 - 添加滚动容器样式:让表格外层容器在小屏幕下自动显示横向滚动条。
修改后的完整代码
CSS
/* 表格容器自适应宽度,小屏幕下显示横向滚动 */ div.dataTables_wrapper { width: 98%; max-width: 100%; margin: 0 auto; overflow-x: auto; } /* 优化滚动体验,避免表头与内容错位 */ table.dataTable { margin: 0 !important; }
JavaScript
$(document).ready(function() { var table = $('#example').DataTable({ // 开启横向滚动,替代默认响应式折叠 scrollX: true, // 保留分页、搜索等核心功能 paging: true, searching: true }); // 保留固定表头功能 new $.fn.dataTable.FixedHeader(table); });
HTML(核心结构无需修改,确保资源引用正确)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap.min.css" /> <link rel="stylesheet" href="https://cdn.datatables.net/fixedheader/3.3.2/css/fixedHeader.bootstrap.min.css" /> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>First name</th> <th>Last name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> <th>Extn.</th> <th>E-mail</th> </tr> </thead> <tbody> <!-- 表格数据保持不变 --> <tr> <td>Tiger</td> <td>Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011-04-25</td> <td>$320,800</td> <td>5421</td> <td>t.nixon@datatables.net</td> </tr> <!-- 其余数据省略 --> </tbody> </table> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap.min.js"></script> <script src="https://cdn.datatables.net/fixedheader/3.3.2/js/dataTables.fixedHeader.min.js"></script>
关键说明
scrollX: true:开启表格横向滚动,当表格宽度超出容器时自动显示滚动条。- 移除
responsive: true:默认响应式插件会将多余列折叠为下拉菜单,与滚动需求冲突。 - 容器
overflow-x: auto:确保小屏幕下表格容器可横向滚动,避免内容挤压变形。
内容的提问来源于stack exchange,提问作者KrupaV
相关产品推荐
相关产品推荐

