針對長表格滾動時表頭固定需求,編寫 jQuery 外掛 CloneTableHeader:複製原表格、提取 <thead>、同步欄寬、插入固定定位的表頭容器。支援 IE6-8、FF、Chrome(但非 IE 寬度計算有誤差)。
jQuery.fn.CloneTableHeader = function(tableId, tableParentDivId) {
// 移除舊實例
var old = document.getElementById("tableHeaderDiv" + tableId);
if (old) $(old).remove();
// 瀏覽器版本偵測(針對 IE8 寬度修正)
var browserName = navigator.appName;
var ver = navigator.appVersion;
var browserVersion = parseFloat(ver.substring(ver.indexOf("MSIE") + 5, ver.lastIndexOf("Windows")));
var content = document.getElementById(tableParentDivId);
var scrollWidth = content.offsetWidth - content.clientWidth; // 捲軸寬度
var $tableOrg = $("#" + tableId);
var $table = $tableOrg.clone().attr("id", "cloneTable");
var $tableHeader = $tableOrg.find("thead");
var tableHeaderHeight = $tableHeader.height();
$tableHeader.hide(); // 隱藏原表頭
// 取得 tbody 第一列每欄寬度
var colsWidths = $tableOrg.find("tbody tr:first td").map(function() {
return $(this).width();
});
// 套用寬度到複製表的 thead
var $cloneCols = $table.find("thead tr:first td");
if (colsWidths.length > 0) {
for (var i = 0; i < $cloneCols.length; i++) {
if (i == $cloneCols.length - 1) {
$cloneCols.eq(i).width(browserVersion == 8.0 ? colsWidths[i] + scrollWidth : colsWidths[i]);
} else {
$cloneCols.eq(i).width(colsWidths[i]);
}
}
}
// 建立固定表頭容器
var headerDiv = document.createElement("div");
headerDiv.appendChild($table[0]);
$(headerDiv).css({
height: tableHeaderHeight,
overflow: "hidden",
"z-index": 20,
width: "100%"
}).attr("id", "tableHeaderDiv" + tableId).insertBefore($tableOrg.parent());
};
<div id="div1" style="height:300px; overflow:auto;">
<table id="tab1">
<thead><tr><th>欄位1</th><th>欄位2</th>...</tr></thead>
<tbody>...大量資料...</tbody>
</table>
</div>
<script>
$(function() {
$.fn.CloneTableHeader("tab1", "div1");
});
</script>
<thead>,凍結目標為 thead 內容。#div1 需設定高度與 overflow:auto 產生捲軸。position: sticky; top: 0; 直接套用於 <th>,零 JS、效能最佳、支援橫向滾動時表頭同步固定。.table-container { height: 300px; overflow: auto; }
table thead th { position: sticky; top: 0; background: #fff; z-index: 1; }