前端固定table表头方法之css和js结合实现

时间:2020-03-27
本文章向大家介绍前端固定table表头方法之css和js结合实现,主要包括前端固定table表头方法之css和js结合实现使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

由于我的页面比较复杂就不贴完整代码了,这里就讲大概思路

先设置css

/** 隐藏滚动条 */
::-webkit-scrollbar {
    width: 8px;
    background-color: transparent;
}
table tbody {
    display: block;
    width: calc(100% + 8px); /*这里的8px是滚动条的宽度*/
    /*height: 600px;*/
    height: auto;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
}
table thead {
    transform: translateY(0px);
    background: #fff;
    z-index: 999;
}
table thead tr, table tbody tr {
    box-sizing: border-box;
    table-layout: fixed;
    display: table;
    width: 100%;
    border-bottom: none;
}

js部分:

// 固定表头
    $(document).scroll(function() {
        var scroH = $(document).scrollTop(); //滚动高度
        if(scroH > 170){ //距离顶部的高度(根据自己实际情况来定):也就是需要固定的地方在滚动到多大距离固定
            var h = scroH - 170
            $("thead").css("transform", 'translateY('+ h+'px)')
        } else {
            $("thead").css("transform", 'translateY(0)')
        }
    });

html大概的结构是:

<table>
    <thead>
      <tr></tr>
  </thead>
  <tbody>
    <tr></tr>
  </tbody>
</table>

原文地址:https://www.cnblogs.com/waterliang/p/12583775.html