拖动滚动条,保持表头固定的HTML写法

这个示例展示了如何在HTML中创建一个带有滚动条的表格,并保持表头在滚动时始终可见。通过使用jQuery和CSS,实现了表头与内容区域的同步滚动和宽度匹配,以提供更好的数据浏览体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js">
</script>
<style>
.bg{
	width:430px;
	overflow-x: scroll;
	position: relative;
}
#table2{
    display: block;
	background-color: #dedede;
	position: absolute;
	left:0;
	top:0;
}
#table2 thead{
	display:block;
}
#table1{
	height: 380px;
    overflow-y: scroll;
    display: block;
}
</style>
</head>

<body>
<div class="bg" style="">
	<table id="table2" border="1px">
		<thead>
			<tr>
				<th>序号</th>
				<th>sdfsdgsgsdg</th>
				<th>dfgccccccccccccccc</th>
				<th>tghrthrhrhh</th>
				<th>yyyyccccccccc</th>
			</tr>
		</thead>
	</table>
	
	<table id="table1" border="1px">
		<thead>
			<tr>
				<th>序号</th>
				<th>sdfsdgsgsdg</th>
				<th>dfgccccccccccccccc</th>
				<th>tghrthrhrhh</th>
				<th>yyyyccccccccc</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>xxx</td>
				<td>2</td>
				<td>32g反反复复反反复复反反复复反反复复反反复复反反复复反反复复反反复复反反复复反反复复反反复复反反复复</td>
				<td><div style="width:50px;word-wrap: break-word;">4defdfdfdfwerwerwerwerwerwerwerwerwrwerwerwerwerwrdfdfdfdfdfdf</div></td>
				<td>反反复复反反复复</td>
			</tr>
			<tr>
				<td>1111111</td>
				<td>2</td>
				<td>32</td>
				<td>4defdfdfdfdfdfdfdfdfdf</td>
				<td>反反复复反反复复</td>
			</tr>
			<tr>
				<td>1111111</td>
				<td>2</td>
				<td>32</td>
				<td>ccc</td>
				<td>反反复复反反复复</td>
			</tr>
			<tr>
				<td>1111111</td>
				<td>2</td>
				<td>32</td>
				<td>4defdfdfdfdfdfdfdfdfdf</td>
				<td>反反复复反反复复</td>
			</tr>
			<tr>
				<td>1111111</td>
				<td>2</td>
				<td>32</td>
				<td>4defdfdfdfdfdfdfdfdfdf</td>
				<td>反反复复反反复复</td>
			</tr>
			<tr>
				<td>1111111</td>
				<td>2</td>
				<td>32</td>
				<td>4defdfdfdfdfdfdfdfdfdf</td>
				<td>333</td>
			</tr>
		</tbody>
	</table>
</div>

<script>
/**
* table2: 展示在最前端的实际表头
* table1: 展示在最前端的实际表格内容
*
* table1是可以上下滚动的窗口
* table2悬浮覆盖在table1上,遮住table1表头
*
* table1中的表头宽度和表格列宽是一致的,就使用table1的表头作为标准,来修改table2的表头宽度
*/
function initTableUI(){
	var tttttt = [];
	$("#table1 thead tr th").each(function(index, jq){
		jq = $(jq);
		tttttt[index] = jq.width();
	});
	
	$("#table2 thead tr th").each(function(index, jq){
		jq = $(jq);
		jq.css("width", tttttt[index]+"px");
	});

	
	$("#table2 thead").css({"width":$("#table1 thead").width()});
	$("#table2").css("width", $("#table2 thead").width() + "px");
	$("#table1").css("width", ($("#table2 thead").width() + 18) + "px");
}
initTableUI();
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值