<!DOCTYPE html>
<html>
<head>
<title>表头悬浮</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<meta charset="UTF-8" />
<script type="text/javascript" src="./jquery.js"></script>
<style>
*{ margin: 0; }
body{ padding: 20px; }
.table{ position: relative; overflow: scroll; }
.table table{ width:1000px }
.table table tbody tr{ line-height: 30px }
.table table tbody tr:nth-child(2n){ background-color: #f1f1f1 }
th,td{ padding: 0 10px; line-height: 30px }
.th_fixed{ width: 1000px; background: #fff; display: none }
.th_fixed span{ display:inline-block;border: 1px solid #000; padding: 0 10px;line-height: 30px;font-weight: 900;text-align: center }
/*隐藏滚轮*/
/*.table::-webkit-scrollbar {
display: none;
}*/
/*隐藏滚轮*/
</style>
</head>
<body>
<div>
<div class="left_hide" ><!-- 超出遮挡 不需要可删除 --></div>
<div class="th_fixed"></div>
<div class="right_hide" ><!-- 超出遮挡 不需要可删除 --></div>
</div>
<div class="table">
<table border="1" cellspacing="0" cellpadding="0" id="table">
<thead>
<tr>
<th>表头</th>
</tr>
</thead>
<tbody>
<tr> <td>表格</td> </tr>
</tbody>
</table>
</div>
</body>
<script>
$(function(){
// 循环创建数据
$('table tr').each(function(){
var html = '';
// console.log($(this).parent().eq(0).prop('tagName'))
// tagName 标签名要大写 THEAD <thead>
if( $(this).parent().eq(0).prop('tagName') == 'THEAD' ){
for( var i = 0; i <= 10; i++ ){
html +='<th>表头'+i+'</th>';
}
}else{
for( var i = 0; i <= 10; i++ ){
html +='<td>表格'+i+i+i+'</td>';
}
}
$(this).html( html )
})
$('tbody').each(function(){
var html = '';
for( var i = 0; i <= 100; i++ ){
html += $(this).html();
}
$(this).html( html )
})
$('tbody tr').each(function(){
$(this).click(function(){
$('tbody tr').css('background','#fff')
$('tbody tr:nth-child(2n)').css('background','#f1f1f1')
$(this).css('background','red')
})
})
// 循环表头创建 悬浮表头
var html ='';
$('thead tr th').each(function(){
html += "<span style=' width:"+$(this).css('width')+";'>"+$(this).html()+"</span>";
})
$('.th_fixed').html(html)
// 设置表格宽高 定位悬浮表头
var table_height = 500;
var table_width = 500;
var table_margin_left = 20;
$('.table').css({ "width":table_width+"px", "height":table_height+"px" });
$('.left_hide').css({"position":"fixed", "z-index":"2", "left":"0","width":table_margin_left+'px', "height":"32px", "background":"#fff" })
$('.right_hide').css({"position":"fixed", "z-index":"2", "left":table_width+table_margin_left+"px","right":'0', "height":"32px", "background":"#fff" })
var th_fixed_left = table_margin_left+1;
$('.table').scroll(function(){
t = $(this).scrollTop();
l = $(this).scrollLeft();
if( l != 0 ){
$('.th_fixed').css({'left':-l+th_fixed_left})
}else{
$('.th_fixed').css({'left':th_fixed_left})
}
if (t > 0) {
$('.th_fixed').css({'position':'fixed',"top":"20px","display":"block","z-index":"1"})
} else {
$('.th_fixed').hide()
}
})
})
</script>
表头悬浮左右滚动
于 2022-08-23 11:23:09 首次发布