这里做个记录,以后还有许多需要优化的地方,不知道支不支持跨行跨列的表格。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>行列固定</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<style>
td, th {
/* 设置td,th宽度高度 */
border:1px solid gray;
width:100px;
height:30px;
}
</style>
</head>
<body>
<div id="main">
<table cellspacing="0" >
<thead>
<tr>
<th>11</th>
<th>22</th>
<th>33</th>
<th>44</th>
<th>55</th>
<th>66</th>
<th>77</th>
<th>88</th>
<th>99</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script>
//模拟数据
var str='';
for(var i=0;i<100;i++){
str+=`<tr>
<td><span>111111111111111111111111111111111111111</span></td>
<td><span>22222222222222222222222222222222222222222222222</span></td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>`;
}
$('#main tbody').eq(0).html(str)
// 定义方法
$.fixTable = function(divId,divWidth,divHeight,tableWidth,fixColumnCount,columnWidthArr,fixBug) {
var background_color="white";//必须设置背景色,因为原理是用z-index实现的
$("#"+divId+" table").css("background-color",background_color);
$("#"+divId+" table th").css("background-color",background_color);
$("#"+divId).css({"width":""+divWidth+"","height":""+divHeight+"","overflow":"auto"});
$("#"+divId+" table").css({"table-layout":"fixed","width":""+tableWidth+""});//table 一定是fixed ,这个不用想
//修改固定列样式
var sumLeft=0;
for(var ff=1;ff<=fixColumnCount;ff++){
if(ff>1){
sumLeft+=parseInt(columnWidthArr[ff-2])+parseInt(fixBug);
}
$("#"+divId+" table td:nth-child("+ff+")").css({"position":"sticky","left":""+((sumLeft)+"px")+"","z-index":"998","background-color":background_color});
$("#"+divId+" table th:nth-child("+ff+")").css({"position":"sticky","left":""+((sumLeft)+"px")+"","z-index":"998","background-color":background_color});
$("#"+divId+" table th:nth-child("+ff+")").css({"z-index":"999","background-color":background_color});
}
// 固定列头
$("#"+divId+" table thead tr th").css({"position":"sticky","top":0});
// 批量修改表格所有列宽度
$("#"+divId+" table th").each(function(i,obj){
$(obj).css('width',columnWidthArr[i])
})
// 文字太多超出宽度,变成...
$("#"+divId+" table tbody td span").each(function(i,obj){
$(obj).addClass('threePoint');
})
$("#"+divId+" table tbody td .threePoint").css(
{"display":"-webkit-box","word-wrap":"break-word","-webkit-line-clamp":"1","text-overflow":"ellipsis","-webkit-box-orient":"vertical","overflow":"hidden"});
};
// 调用方法
// 1: divId
// 2: div宽度
// 3: div高度
// 4: table宽度
// 5: 固定列数
// 6: 所有列宽度数组
// 7: 不明原因的抖动,看情况填写
$.fixTable('main','1024','300','200',3,['100','200','300','300','300','300','300','300','300'],4)
</script>
</html>
效果图