長表格捲動時表頭會跑掉,使用者看到一堆數字卻不知道每欄代表什麼。解法是把 thead 複製一份放到表格外面固定住,並讓它隨外層容器的橫向捲動同步移動。這篇把整個外掛與使用範例都列出來。
jQuery.fn.CloneTableHeader = function (tableId, tableParentDivId) {
// 避免重複呼叫時產生多個表頭
var obj = document.getElementById("tableHeaderDiv" + tableId);
if (obj) {
jQuery(obj).remove();
}
// 取得外層捲動容器的資訊
var content = document.getElementById(tableParentDivId);
var scrollWidth = content.offsetWidth - content.clientWidth; // 垂直滾動條寬度
var tableOrg = jQuery("#" + tableId);
// 複製整個表格,稍後只取它的 thead
var table = tableOrg.clone();
table.attr("id", "cloneTable");
// 隱藏原表格的 thead(但仍保留佔位)
var tableHeader = jQuery(tableOrg).find("thead");
var tableHeaderHeight = tableHeader.height();
tableHeader.hide();
// 量出 tbody 第一列每個 td 的實際寬度
var colsWidths = jQuery(tableOrg).find("tbody tr:first td").map(function () {
return jQuery(this).width();
});
// 把量到的寬度套到複製表格的 thead 上
var tableCloneCols = jQuery(table).find("thead tr:first td");
if (colsWidths.size() > 0) {
for (var i = 0; i < tableCloneCols.size(); i++) {
// 最後一欄要額外補上滾動條寬度,否則會對不齊
if (i == tableCloneCols.size() - 1) {
tableCloneCols.eq(i).width(colsWidths[i]);
} else {
tableCloneCols.eq(i).width(colsWidths[i]);
}
}
}
// 建立一個固定高度的容器包住複製的 thead
var headerDiv = document.createElement("div");
headerDiv.appendChild(table[0]);
jQuery(headerDiv).css("height", tableHeaderHeight);
jQuery(headerDiv).css("overflow", "hidden");
jQuery(headerDiv).css("z-index", "20");
jQuery(headerDiv).css("width", "100%");
jQuery(headerDiv).attr("id", "tableHeaderDiv" + tableId);
// 插到原表格的父元素之前
jQuery(headerDiv).insertBefore(tableOrg.parent());
};
<!DOCTYPE html>
<html>
<head runat="server">
<title>jQuery 實現表頭固定效果</title>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="jQuery_FixedTableHead.js" type="text/javascript"></script>
<style type="text/css">
.itemList {
border: solid 1px #cccccc;
width: 100%;
border-collapse: collapse;
}
.itemList td {
padding: 0px;
color: #444444;
border: solid 1px #cccccc;
text-align: center;
line-height: 20px;
}
</style>
<script type="text/javascript">
jQuery(function() {
jQuery.fn.CloneTableHeader("tab1", "div1");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 250px; overflow: scroll;" id="div1">
<table cellpadding="0" id="tab1" cellspacing="0" border="0" class="itemList">
<thead>
<tr style="background-color:#eeeeee; line-height:20px; font-weight:bold;">
<td>列1</td>
<td>列2</td>
<td>列3</td>
<td>列4</td>
</tr>
</thead>
<tbody>
<tr><td>我是測試的數據行</td><td>我是測試的數據行</td>
<td>我是測試的數據行</td><td>我是測試的數據行</td></tr>
<!-- 重複多列以產生垂直滾動 -->
</tbody>
</table>
</div>
</form>
</body>
</html>
注意:記得引入 jQuery 類庫檔案,並確認外掛的引入順序在 jQuery 之後。
整體思路是「複製 thead → 隱藏原本的 thead → 把複製件放在表格上方固定」。三個細節決定成敗:
欄寬必須重新量測。複製出來的 thead 是獨立元素,瀏覽器會依自己的演算法重新分配欄寬,跟原表格對不齊。所以要先量出 tbody 第一列每個 td 的實際寬度,再逐一寫回複製件的 td,強制對齊。
最後一欄要補滾動條寬度。外層 div 有 overflow:scroll,會佔去約 17px(依平台而異)。原表格的可用寬度已經扣掉了這部分,但複製出的表頭容器沒有滾動條,所以最後一欄若不補上這個差值,就會比原表格窄一截。原範例在 IE8 下做了 + scrollWidth 的補償,其他瀏覽器則沒有——這其實應該所有瀏覽器都補才對。
橫向捲動要同步。目前這個版本只處理了垂直捲動時表頭固定。當使用者左右捲動時,複製的表頭不會跟著動,就會與內容錯位。需要額外監聽外層容器的 scroll 事件,把 scrollLeft 套到表頭容器上。
用了已移除的 API。.size() 在 jQuery 3 已移除,請改用 .length。另外 navigator.appName 與字串解析 appVersion 來判斷版本的寫法早已不可靠,現在該用 navigator.userAgent 搭配 feature detection。
依賴 thead/tbody 的存在。整個程式假設表格有明確的 thead 與 tbody。若表格沒有寫 thead,tableHeader.height() 會是 undefined,後續就全錯。
不處理資料變動。如果表格內容會動態更新(例如 AJAX 載入更多列、欄寬因內容而改變),表頭不會自動重新對齊。需要提供一個重新呼叫的機制。
如果目標只是「表頭固定」,CSS 已經有現成方案,不需要 JavaScript:
/* 方法一:position: sticky(最簡單, IE 不支援) */
thead th {
position: sticky;
top: 0;
background: #eee;
z-index: 10;
}
/* 方法二:display: block + 滾動容器 */
.table-scroll {
max-height: 400px;
overflow-y: auto;
}
table { border-collapse: separate; border-spacing: 0; }
thead th {
position: sticky;
top: 0;
background: #eee;
}
position: sticky 一行就解決問題,而且天然處理欄寬對齊(因為表頭本來就是同一個 table 的一部分)。它支援所有現代瀏覽器,只有 IE 不支援。
若需要更多功能(欄位排序、凍結多欄、虛擬滾動),直接採用成熟套件會更划算。而對於資料量大的情況,重點其實不在表頭,而在分頁或虛擬滾動——與其讓使用者捲過 500 列,不如一次只給 50 列。