表格一長就要捲動,捲一捲標題就不見了。在還需要支援 IE 的年代,有一個不用寫太多 JavaScript 的做法:靠 CSS expression 讓標題列與左側欄位隨著捲軸反向位移,視覺上就達到「凍結」的效果。
.FixedTitleRow {
position: relative;
top: expression(this.offsetParent.scrollTop);
z-index: 10;
width: 80px;
background-color: #FFCC00;
}
.FixedDataColumn {
position: relative;
left: expression(this.parentElement.offsetParent.parentElement.scrollLeft);
background-color: #E6ECF0;
}
.FixedColumnAndRows {
position: relative;
top: expression(this.offsetParent.scrollTop);
left: expression(this.offsetParent.scrollLeft);
z-index: 20;
width: 80px;
background-color: #FFCC00;
}
td { word-break: keep-all; }
FixedTitleRow 用在表頭右側的儲存格,只補償垂直捲動;FixedDataColumn 用在左側欄位,只補償水平捲動;FixedColumnAndRows 則是左上角那個「兩邊都要固定」的交集格,z-index 也設得最高,確保它永遠壓在最上層。
<div id="scrollDiv" style="width:500; height:150; overflow:auto; cursor:default; display:inline; position:absolute;">
<table width="100%" cellpadding="0" cellspacing="0" bordercolor="lightgrey" border="1" style="table-layout:fixed">
<tr bgcolor="#FFCC00" style="font-size:12px; text-align:center; font-weight:bold; height:25px;">
<td class="FixedColumnAndRows">header</td>
<td class="FixedColumnAndRows">header</td>
<td class="FixedColumnAndRows">header</td>
<td class="FixedTitleRow">header</td>
<td class="FixedTitleRow">header</td>
<td class="FixedTitleRow">header</td>
<td class="FixedTitleRow">header</td>
<td class="FixedTitleRow">header</td>
</tr>
<tr style="font-size:12px; text-align:center; height:20px;">
<td class="FixedDataColumn">left</td>
<td class="FixedDataColumn">left</td>
<td class="FixedDataColumn">left</td>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
</tr>
<!-- 其餘資料列沿用相同結構 -->
</table>
</div>
這種凍結行列的方式只適用於 IE,而且只適合資料量少的情況。原因是 expression 會在每次捲動時重新求值並觸發重繪,資料一多就會非常耗資源,捲起來明顯卡頓。
在現代瀏覽器中,同樣的效果有更好的解法:表頭用 position: sticky 就能凍結,不必任何 JavaScript;若需要同時凍結欄與列,則可搭配兩個各自獨立捲動的容器同步 scrollLeft/scrollTop。這些做法跨瀏覽器一致,效能也遠優於 expression。