還記得之前公司需要做表頭固定,但是由于基礎(chǔ)太差,去查了好多好多文檔。最后總結(jié)出幾個(gè)不錯(cuò)的方法和插件。
一、使用css + js來實(shí)現(xiàn)表頭固定

項(xiàng)目demo
使用css定位th 根據(jù)父級(jí)滾動(dòng)條scrolltop的偏移量獲取值,在用js把偏移量賦值到th的定位top上。就做到了表頭固定。(此方法需要固定高度)
項(xiàng)目demo
css樣式部分 主要是出現(xiàn)滾動(dòng)條和定位th還有固定高度。
<style>
.table-responsive {
overflow: auto !important;
}
.table-th-css {
background: #EFEFF4 !important;
position: relative !important;
text-align: center;
top: 0;
}
.section-scroll{
height:417px;
}
</style>
html部分 自己做肯定內(nèi)容超級(jí)多 demo我就不復(fù)制那么多內(nèi)容了。
<div class="table-responsive section-scroll">
<table class="table table-bordered">
<thead class="table-header">
<tr>
<th class="table-th-css">
<div>部門</div>
</th>
<th class="table-th-css">
<div>用戶名稱</div>
</th>
<th class="text-center table-th-css">
<div>1月</div>
</th>
<th class="text-center table-th-css">
<div>2月</div>
</th>
<th class="text-center table-th-css">
<div>3月</div>
</th>
<th class="text-center table-th-css">
<div>4月</div>
</th>
<th class="text-center table-th-css">
<div>5月</div>
</th>
<th class="text-center table-th-css">
<div>6月</div>
</th>
<th class="text-center table-th-css">
<div>7月</div>
</th>
<th class="text-center table-th-css">
<div>8月</div>
</th>
<th class="text-center table-th-css">
<div>9月</div>
</th>
<th class="text-center table-th-css">
<div>10月</div>
</th>
<th class="text-center table-th-css">
<div>11月</div>
</th>
<th class="text-center table-th-css">
<div>12月</div>
</th>
<th class="text-center table-th-css">
<div>合計(jì)</div>
</th>
</tr>
</thead>
<tbody >
<tr class="text-center" >
<td >
多毛大叔愛蘿莉
</td>
<td class="table-textWidth">
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
<td>
多毛大叔愛蘿莉
</td>
</tr>
</tbody>
</table>
</div>
js內(nèi)容 使用jq的on事件,監(jiān)聽滾動(dòng)根據(jù)我自己項(xiàng)目的樣式修改了下自己的樣式。大家使用可自行調(diào)整。
var tableCont = $('.section-scroll tr th'); //獲取th
var tableCont_child = $('.section-scroll tr th div'); //獲取th下邊的div
var tableScroll = $('.section-scroll'); //獲取滾動(dòng)條同級(jí)的class
function scrollHandle() {
var scrollTop = tableScroll.scrollTop();
// 當(dāng)滾動(dòng)距離大于0時(shí)設(shè)置top及相應(yīng)的樣式
if (scrollTop > 0) {
tableCont.css({
"top": scrollTop + 'px',
"marginTop": "-1px",
"padding": 0
});
tableCont_child.css({
"borderTop": "1px solid gainsboro",
"borderBottom": "1px solid gainsboro",
"marginTop": "-1px",
"padding": "8px"
})
} else {
// 當(dāng)滾動(dòng)距離小于0時(shí)設(shè)置top及相應(yīng)的樣式
tableCont.css({
"top": scrollTop + 'px',
"marginTop": "0",
});
tableCont_child.css({
"border": "none",
"marginTop": 0,
"marginBottom": 0,
})
}
}
tableScroll.on('scroll', scrollHandle);
這樣第一種方式的表頭固定就完成了。在瀏覽器上看著基本沒瑕疵,但是我用mui使用這種方法,可能是app的滾動(dòng)有回彈所以效果會(huì)顯得有點(diǎn)卡頓。本人菜雞不喜勿噴(歡迎回復(fù)..)。