js、css 实现table表头固定

1.  js实现(个人项目用过,完全js实现)

html:

<div class='table-cont' id='table-cont'><!--看这里--> 
   <table class="table table-striped">
      <thead>
        <tr>
          <th>11</th><th>22</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>33</td><td>44</td>
        </tr>
        <tr>
          <td>55</td><td>66</td>
        </tr>
      </tbody>
    </table>
  </div>

css:

/* table-cont为table外层div的class*/

.table-cont{
  /**make table can scroll**/
  max-height: 200px;
  overflow: auto;
  /** add some style**/
  /*padding: 2px;*/
  background: #ddd;
  margin: 20px 10px;
  box-shadow: 0 0 1px 3px #ddd;
}
thead{
  background-color: #ddd;
}

js:

// 固定表头
'use strict'
 window.onload = function(){
  var tableCont = document.querySelector('#table-cont')
  function scrollHandle (e){
    console.log(this)
    var scrollTop = this.scrollTop;
    this.querySelector('thead').style.transform = 'translateY(' + scrollTop +'px)';
  }  
  tableCont.addEventListener('scroll',scrollHandle)
}

方法二:纯css样式实现(简单的table,没有复杂多级嵌套的table可以用这个方法。。。)

html:

 <table align="center">
       <thead>
           <tr> <th>序号</th><th>内容</th> </tr>
       </thead>
       <tbody>
           <tr> <td>1</td><td>我只是用来测试的</td> </tr>
           <tr> <td>2</td><td>我只是用来测试的</td> </tr>
           <tr> <td>3</td><td>我只是用来测试的</td> </tr>
        </tbody>
</table>

css:

    <style>
        table tbody {
            display: block;
            height: 200px;
            overflow-y: scroll;
        }

        table thead tr,
        table tbody tr {
            display: table;
            width: 100%;
            table-layout: fixed;
            text-align: center;
        }

        thead th,
        tbody td {
            width: 50px;
        }

        table thead {
            width: calc( 100% - 1em);
        }
    </style>

效果图:

 

 

 

参考:https://www.jianshu.com/p/27315ff5f52d

 

 

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值