前端固定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>

 

相关文章