當表格內容過多需要捲動時,我們往往希望標題列(表頭)和關鍵的資料列能被「固定」住,捲動時保持可見。本文介紹一種利用 IE 特有的 CSS expression 實現固定行列的方法。
透過 expression 動態計算元素的定位,讓表頭隨垂直捲動保持頂部對齊、左側欄隨水平捲動保持可見。這種方式在 IE 下實現固定行列相當便捷。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> New Document </title>
<style>
.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;}
</style>
</head>
<body>
<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>
<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>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
</tr>
</table>
</body>
</html>
/* 這種固定行列的方式只適用於IE,並且只適用於數據量較少的情況.數據量很多時是非常耗資源的!*/
程式碼定義了三個關鍵樣式:FixedTitleRow 固定標題列(隨垂直捲動對齊頂部)、FixedDataColumn 固定左側資料欄(隨水平捲動對齊左側)、FixedColumnAndRows 則同時固定左上角交叉區域,並以較高的 z-index 確保它始終在最上層。
重要提醒:這種基於 CSS expression 的固定方式僅適用於 IE,且只適合資料量較少的情況——因為 expression 會持續重算,資料一多就非常耗費資源。在現代開發中,建議改用更標準、效能更佳的方案(如 position: sticky)來實現類似效果。