您的位置:首页 > Web前端 > HTML

html固定table表头的实现思路

2017-12-21 00:00 666 查看
实现步骤

1.将table放在可滚动容器中;
2.可滚动容器外层还需要一个容器,这个容器需设置超出范围隐藏和定位(相对、绝对都行);
3.利用脚本克隆一个目标table,调整克隆table的列宽与原table相同,隐藏tbody,追加到外层的容器中;
4.监听滚动容器的滚动事件,动态调整克隆table的左偏移,上偏移不需要调整,因为已经固定了。

效果演示

<html>
<head>
<style>
.tablebox{height:300px;overflow:auto;width:100%;}
.tableboxcontainer table td{white-space:nowrap;}
.tableboxcontainer table thead{background:#ddd;}
.tableboxcontainer{position:relative;width:300px;overflow:hidden;}
</style>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="tableboxcontainer">
<div class="tablebox" id="tablebox">
<table class="table">
<thead>
<tr>
<td>列1</td><td>列2</td><td>列3</td><td>列4</td><td>列5</td>
<td>列6</td><td>列7</td><td>列8</td><td>列9</td><td>列10</td>
</tr>
</thead>
<tbody>

</tbody>
</table>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
//生成表格测试数据
var $table=$("#tablebox").find("table");
var $tbody=$table.find("tbody");
for(var i=0;i<20;i++){
var $tr=$("<tr>");
for(var j=0;j<10;j++){
$tr.append(function(){
return $("<td>").text("行:"+(i+1)+"列:"+(j+1));
});
}
$tr.appendTo($tbody);
}
//克隆原表,追加到最外层容器中
var $table_fixed=$table.clone();
var colwidths=[];
//设置克隆表的列宽
$tbody.find("tr:eq(0)").find("td").each(function(){
var width=$(this).width()+parseFloat($(this).css("padding-left"))+parseFloat($(this).css("padding-right"));
colwidths.push(width);
});
$table_fixed.find("thead td").each(function(i){
$(this).width(colwidths);
});
$table_fixed.css({"position":"absolute","left":0,"top":0,"table-layout":"fixed"});
$table_fixed.find("tbody").hide();//隐藏克隆表的tbody
$("#tablebox").parent().append($table_fixed);
//监听原表容器的滚动事件
$("#tablebox").bind("scroll",function(){
var left=$(this).scrollLeft();
$table_fixed.css({"left":-left});
});
});
</script>
</body>
</html>

WEB前端互动交流群 434623999
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: