Bootstrap固定高度表格滚动时表头固定问题(重复<tbody>场景)
解决重复使用
<tbody>时Bootstrap表格表头无法固定的问题 我之前也碰到过类似的场景,你的问题核心在于把整个表格都放在了滚动容器内,所以滚动时表头会跟着表体一起移动。咱们可以通过拆分表头和表体的结构来实现表头固定,同时保留你重复使用<tbody>的需求,具体方案如下:
核心思路
将表头和滚动的表体拆分为两个独立的表格,让表头始终停留在顶部,只让表体部分滚动。同时通过CSS保证两个表格的列宽完全对齐,避免出现错位。
修改后的完整代码
CSS 部分
/* 表头表格:固定在顶部,列宽和表体一致 */ .fixed-header-table { width: 238px; table-layout: fixed; border-bottom: none; } /* 表体容器:设置固定高度和滚动 */ .table-scroll-body { width: 238px; overflow-y: auto; max-height: 140px; } /* 表体表格:和表头列宽对齐,去掉顶部边框避免重复 */ .scroll-body-table { width: 100%; table-layout: fixed; border-top: none; }
HTML 部分
<!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="style.css" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-controller="MyCtrl"> <!-- 固定表头的表格 --> <table class="table fixed-header-table"> <thead> <tr class="summary-table-header"> <th>Season</th> <th>2018</th> <th>2019</th> <th>2020 </th> <th>2021 </th> </tr> </thead> </table> <!-- 滚动的表体容器 --> <div class="table-scroll-body"> <table class="table scroll-body-table"> <!-- 保留你原来的<tbody>重复逻辑 --> <tbody ng-repeat="item in seasons"> <tr style="cursor:pointer"> <td>{{item.season}}</td> <td>{{item.2018}}</td> <td>{{item.2019}}</td> <td>{{item.2020}}</td> <td>{{item.2021}}</td> </tr> </tbody> </table> </div> </div> </body> </html>
关键细节说明
table-layout: fixed:这个属性强制表格按设置的宽度分配列宽,确保表头和表体的列完全对齐,不会因为内容长度变化导致错位。- 拆分表格后,通过
border-bottom: none和border-top: none去掉两个表格连接处的重复边框,视觉上更像一个完整的表格。 - 我还修正了你HTML里的小问题:原来的
<td>绑定的年份和$scope.seasons里的字段不匹配(比如item.2017在数据中不存在),现在已经调整成对应字段了。
内容的提问来源于stack exchange,提问作者forgottofly
相关产品推荐
相关产品推荐

