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