如何将html中表格头部固定
- 作者 : zfajax舫
- |
- 发布时间 : 6年前
- |
- 评论数 : 0
- 查看数 : 45
编写一个测试的表格
<div class="table-responsive section-scroll" style="height: 600px;">
<table class="table table-bordered" >
<thead class="table-header">
<tr style="background: #ffffff;">
<td style="position: relative"> <div style="background: #ffffff;">序号</div></td>
<td width="61" style="position: relative;"><div style="background: #ffffff;">地域</div></td>
<td width="119" style="position: relative;"><div style="background: #ffffff;">国家(地区)名称</div></td>
<td width="208" style="position: relative;"><div style="background: #ffffff;">网址</div></td>
<td width="236" style="position: relative;"><div style="background: #ffffff;">电话</div></td>
<td width="110" style="position: relative;"><div style="background: #ffffff;">传真</div></td>
<td width="152" style="position: relative;"><div style="background: #ffffff;">E-mail</div></td>
<td width="201" style="position: relative;"><div style="background: #ffffff;">联系地址</div></td>
</tr>
</thead>
<tbody>
.
.
.
</tbody>
</table>
</div>
</div>
编写JavaScript
<script>
$(function() {
var tableCont = $('.section-scroll thead tr td'); //获取td
var tableCont_child = $('.section-scroll thead tr td div'); //获取th下边的div
var tableScroll = $('.section-scroll'); //获取滚动条同级的class
function scrollHandle() {
var scrollTop = tableScroll.scrollTop();
// 当滚动距离大于0时设置top及相应的样式
if (scrollTop > 0) {
tableCont.css({
"top": scrollTop + 'px',
"marginTop": "-1px",
"padding": 0
});
tableCont_child.css({
"borderTop": "1px solid gainsboro",
"borderBottom": "1px solid gainsboro",
"marginTop": "-1px",
"padding": "8px"
})
} else {
// 当滚动距离小于0时设置top及相应的样式
tableCont.css({
"top": scrollTop + 'px',
"marginTop": "0",
});
tableCont_child.css({
"border": "none",
"marginTop": 0,
"marginBottom": 0,
})
}
}
tableScroll.on('scroll', scrollHandle);
})
</script