長表格滾動時,表頭固定在視口頂部,方便對照列含義。項目已用 jQuery + 純 HTML,需最小改動實現。
<table id="dataTable">
<thead>
<tr class="header"><td width="150"></td><td colspan="2"></td><td colspan="7">師資力量</td><td colspan="14">科研</td><td></td></tr>
<tr class="header"><td></td><td colspan="2">人才培養</td><td colspan="3">職稱結構</td>...</tr>
<tr class="header"><td>教學單位</td><td>本科生數</td>...</tr>
</thead>
<tbody>...</tbody>
</table>
<!-- 佔位行,防止浮動表頭遮擋內容 -->
<tr id="hiddenTd"><td colspan="28"></td></tr>
$(window).scroll(function() {
var $headers = $('.header'); // 3 行表頭
var scrollTop = $(this).scrollTop(); // 文檔滾動距離
var headerOffset = 55; // 表頭距離頁面頂部的初始偏移(需根據實際布局測量)
if (scrollTop > headerOffset) {
var fixedTop = scrollTop - headerOffset;
// 逐行設置 absolute 定位,模擬 fixed 效果(避免 fixed 脫離表格流導致列寬錯位)
$headers.eq(0).css({ position: 'absolute', top: fixedTop });
$headers.eq(1).css({ position: 'absolute', top: fixedTop + $headers.eq(0).outerHeight() });
$headers.eq(2).css({ position: 'absolute', top: fixedTop + $headers.eq(0).outerHeight() + $headers.eq(1).outerHeight() });
// 佔位行高度 = 表頭總高,撐開空間防止內容上移被遮擋
$('#hiddenTd').height($headers.eq(0).outerHeight() + $headers.eq(1).outerHeight() + $headers.eq(2).outerHeight());
} else {
// 滾回頂部區域,恢復靜態定位
$headers.css({ position: 'static', top: '' });
$('#hiddenTd').height(0);
}
});
position:fixed 會使表頭脫離表格流,導致列寬與 tbody 不對齊。absolute 相對最近定位祖先(通常是 table 或包裹 div),保持列寬同步。top = 固定基準 + 前 N-1 行高度之和。#hiddenTd 高度等於表頭總高,補償 absolute 脫離文檔流導致的內容上移。rowspan,浮動時極易錯位,拆分為多行 colspan 更穩健。<style>
#dataTable thead th {
position: sticky;
top: 0;
z-index: 1;
background: #fff; /* 避免內容滾動時穿透 */
}
</style>
// 同理,監聽橫向滾動,固定第一列
$(window).on('scroll', function() {
var left = $(this).scrollLeft();
$('#dataTable th:first-child, #dataTable td:first-child').css({ position: 'absolute', left: left });
});
結合垂直 + 水平固定,實現 Excel 風格凍結窗格。