[关闭]
@TedZhou 2018-11-29T07:16:46.000000Z 字数 1209 阅读 471

让table固定表头并冻结列的一种简单实现方法

html css javascript 技术


标题已经说明需求,就不说废话了,直接上code;)

.html

  1. <!--把table放到div容器里。-->
  2. <div class="table-container">
  3. <table class="table-fixed">
  4. <thead>
  5. <tr>
  6. <th class="col-fixed">fixed0</th>
  7. <th>column0</th>
  8. ...省略其它th...
  9. </tr>
  10. </thead>
  11. <tbody>
  12. <tr>
  13. <td class="col-fixed">fixed1</td>
  14. <td>column1</td>
  15. ....省略其它td...
  16. </tr>
  17. ....省略其它tr...
  18. </tbody>
  19. </table>
  20. <div>

.css

  1. <style>
  2. /*限制容器宽高并允许滚动*/
  3. .table-container{
  4. width:100%;
  5. max-height:200px;
  6. overflow:auto;
  7. }
  8. /*表头cell设为相对定位*/
  9. .table-fixed>thead>tr>th{
  10. position:relative;
  11. z-index:100;
  12. background-color:#eee;
  13. }
  14. /*冻结列设为相对定位*/
  15. .table-fixed>tbody>tr>td.col-fixed{
  16. position:relative;
  17. background-color:#eee;
  18. }
  19. /*设置z-index避免被覆盖*/
  20. .table-fixed>thead>tr>th.col-fixed{
  21. z-index:110;
  22. }
  23. </style>

.js

  1. <script>
  2. //需先引入jquery
  3. $(function(){
  4. var $table = $('.table-fixed');
  5. var $topFixes = $table.find('thead>tr>th');
  6. var $colFixes = $table.find('.col-fixed');
  7. //容器滚动时,为实现fixed冻结效果:
  8. //1、把表头cell的top设为scrollTop
  9. //2、冻结列的left设为scrollLeft
  10. $table.closest('.table-container').scroll(function(){
  11. $topFixes.css('top',this.scrollTop);
  12. $colFixes.css('left',this.scrollLeft);
  13. });
  14. });
  15. </script>

总结

相较于表头和内容分离的做法,这种实现方式不会出现对不齐的问题,而且比较简单(:不想写js的请忽略)

已知问题

  1. 桌面Chrome下的效果最好,其他浏览器fixed内容有点闪烁。
  2. 移动端浏览器下的延迟比较严重,只能改为用多个table实现。
  3. 如果冻结列超出容器(.table-container)的范围,会导致水平滚动条滚不到头(无限滚动)。
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注