HTML表头固定,内容滚动实现
在前端开发过程中,经常会遇到⼀个需求就是,需要⼀个表格展⽰数据,
1、表头固定,内容过多的时候向下活动,表头不跟随移动,若表体内容超长时,表头不能移动,表体内容滚动显⽰;
2、表格头横向随表格内容横向滚动;
效果展⽰:
关键技术点:
1、表头(意义上的)和表体(意义上的)都⽤⼀个table来显⽰;
2、因为表体可以纵向滚动,右边多出⼀个纵向滚动条,所以表体的宽度要⽐表头的宽度多出17个像素,也就是说,如果要设置表格的宽度是500的话,表体的宽度为100%,那表头的宽度就是减去17个像素,就是calc(100% - 17px);
3、列宽要固定,两个table节点的table-layout样式为fixed
代码展⽰:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.table {
border: solid 1px #ddd;
width: 100%;
display: inline-block;
}
th, td {
border-right: solid #ddd 1px;
border-bottom: solid #ddd 1px;
}
th {
background-color: #ddd;
}
</style>
</head>
<body>
<div >
<div ref="table" class="table">
<div id="table-head">
<table >
<thead>
<tr>
<tr>
<th >姓名</th>
<th >性别</th>
<th >省份证号</th>
<th >省份证号</th>
<th >省份证号</th>
</tr>
</thead>
</table>
</div>
<div id="table-body"> <table >
<tbody>
<tr>
<td >张三开始</td>
<td >男</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >
<img src="//www.baidu/img/bd_logo1.png" > <img src="//www.baidu/img/bd_logo1.png" > <img src="//www.baidu/img/bd_logo1.png" > <img src="//www.baidu/img/bd_logo1.png" > <img src="//www.baidu/img/bd_logo1.png" > </td>
</tr>
<tr>
<td >张三1</td>
<td >男</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
</tr>
<tr>
<td >张三2</td>
<td >男</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
</tr>
<tr>
<td >张三</td>
html横向滚动条样式<td >男</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
</tr>
<tr>
<td >张三</td>
<td >男</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
</tr>
<tr>
<td >张三</td>
<td >男</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
</tr>
<tr>
<td >张三</td>
<td >男</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td>
<td >xxxxxxxxxxxxxxxxxxx</td> <td >xxxxxxxxxxxxxxxxxxx</td> </tr>
<tr>
<td >张三结束</td>
<td >男</td>
<td >xxxxxxxxxxxxxxxxxxx</td> <td >xxxxxxxxxxxxxxxxxxx</td> <td >xxxxxxxxxxxxxxxxxxx</td> </tr>
</tbody>
</table>
</div>
</div>
</div>
<script src="../../../src/lib/jquery/jquery-1.12.4.min.js"></script> <script type="text/javascript">
var $tableHead = $('#table-head');
var $tableBody = $('#table-body');
/*设置同步横向滚动*/
$tableBody.scroll(function (ev) {
$tableHead.scrollLeft($tableBody.scrollLeft()); // 横向滚动条 });
</script>
</body>
</html>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论