table表格固定表头

柴嘉石
2023-12-01

table表格内容过多时会出现滚动,若不固定表头的话,当滚动到下方时即看不见每一列所对应的标题,影响用户体验!

废话不多说,直接上代码!!!

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>固定表头</title>
		<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	</head>
	<style type="text/css">
		.tableHeader {
			position: sticky;
			top: -1px;
			display: none;
			background-color: #7dc3ff;
			table-layout: fixed;
		}
	</style>
	<body>
		<div class="col-lg-12">
			<table class="table table-bordered table-hover tableHeader">
				<thead>
					<tr>
						<th>ID</th>
						<th>表头1</th>
						<th>表头2</th>
						<th>表头3</th>
						<th>其他</th>
					</tr>
				</thead>
			</table>
			<table class="table table-bordered table-hover tableBody" style="table-layout: fixed;">
				<thead>
					<tr>
						<th>ID</th>
						<th>表头1</th>
						<th>表头2</th>
						<th>表头3</th>
						<th>其他</th>
					</tr>
				</thead>
				<tbody>

				</tbody>
			</table>
		</div>
	</body>
	<script type="text/javascript">
		var str = ''
		for (var i = 0; i < 100; i++) {
			str += "<tr>" + "<td>" + (i + 1) + "</td>" + "<td>" + '哈哈1' + "</td>" + "<td>" + '哈哈2' + "</td>" + "<td>" + '哈哈3' +
				"</td>" + "<td>" + '哈哈4' + "</td>" + "</tr>"
		}
		document.querySelector(".tableBody>tbody").innerHTML = str
		window.onscroll = function() {
			var d = document.documentElement.scrollTop
			if (d >= 40) {
				document.querySelector(".tableHeader").style.display = "inline-table"
			} else {
				document.querySelector(".tableHeader").style.display = "none"
			}
		}
	</script>
</html>

 类似资料: