html
<div class="mybox" style="height: 100vh;position: absolute;top: 0;"></div>
<div class="table-list">
<table>
<thead>
<tr>
<th>表头</th>
</tr>
</thead>
<tbody>
<tr>
<td>内容</td>
</tr>
</tbody>
</table>
</div>
css
.table-list thead tr{background: #eef3f7;}
.table-list{width: 100%; overflow: auto; }
.table-list th,.table-list td{white-space: nowrap;}
.table-list th { background-color: #fff; position: sticky; top: 0px; }
.table-list th:nth-child(-n+5) { position: sticky; top: 0px; z-index: 10; }
.table-list td:nth-child(-n+5) { background-color: #fff; position: sticky; }
.table-list th:first-child,.table-list td:first-child{ left: 0px; }
js
// 表格滚动
roll()
$(window).resize(function(){
roll()
})
function roll(){
var myheight = $('.mybox').height();
var tableheight = $('.table-list table').height();
var conheight = myheight-178 // 178是查询条件的固定高度,减去之后就是表格的高度自适应
if(tableheight<=conheight){
conheight = tableheight;
}
$('.table-list').height(conheight);
var $fixedColumns = $('table tr').find('td').slice(1, 5);
// 计算每列的宽度
var columnWidths = [];
var fixedWidth = 0;
$fixedColumns.each(function(index) {
fixedWidth += parseInt($(this).outerWidth());
columnWidths.push(fixedWidth);
});
$('table tr').each(function() {
$(this).find('td').slice(1, 5).each(function(index) {
$(this).css('left', columnWidths[index] + 'px');
});
$(this).find('th').slice(1, 5).each(function(index) {
$(this).css('left', columnWidths[index] + 'px');
});
});
}