由于是基于bootstrap基础,所以样式有些需要修改
主要用到的样式
<style>
body {
padding-top: 100px;
}
.scrollTable, .fixTable{width:100%;max-width:none;}
.nowrap tr th, .nowrap tr td{white-space:nowrap;}
#outtableDiv {
padding: 0;
height: 400px;
overflow-y: scroll;
overflow-x: scroll;
}
.fixTable thead {
background-color: #fff;
}
.fixTable{margin-bottom:0;position:absolute;
background-color: #fff; }
</style>
主要html结构
<div id="outtableDiv" class="col-xs-12" >
<table id="fixTable" class="table table-bordered fixTable nowrap">
<thead>
<tr>
<th colspan="2">姓名姓名</th>
<th>性别</th>
<th colspan="2">身高</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
</tr>
<tr>
<th>姓名姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
</tr>
</thead>
</table>
<table id="textTable" class="table table-bordered scrollTable nowrap">
<thead>
<tr>
<th>姓名姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
</tr>
<tr>
<th>姓名姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>身高</th>
<th>体重</th>
</tr>
</thead>
<tbody id="testTbody">
</tbody>
</table>
用到的js
<script type="text/javascript">
$(document).ready(function () {
function duiqi(){
var fixTh=$("#fixTable tr:last-child th");
var contentTh=$("#textTable tr:last-child th");
var contentTableWidth=$("#textTable").outerWidth();
$("#fixTable").outerWidth(contentTableWidth);
for(i=0;i<contentTh.length;i++){
fixTh.eq(i).outerWidth(contentTh.eq(i).outerWidth());
}
}
$('#outtableDiv').scroll(function() {
var scrollTop=$('#outtableDiv').scrollTop();
$("#fixTable").css("top",scrollTop);
})
duiqi();
$(window).resize(function () {
duiqi();
});
})
</script>
缺点是每次滚动都是不停的计算scrollTop的值,把他赋给固定头的样式
$('#outtableDiv').scroll(function() { var scrollTop=$('#outtableDiv').scrollTop(); $("#fixTable").css("top",scrollTop); })
(adsbygoogle = window.adsbygoogle || []).push({});