position: fixed 做固定浮動層非常方便,但 IE6 及以下完全不支援。網路上常見的解法是 JS 監聽滾動事件再改 top,缺點是拖動滾動條時會明顯抖動。下面這個 demo 改用 CSS expression 處理,涵蓋上下左右四種固定位置,IE5、IE6 都能正常運作,且在 quirks 模式下也沒問題。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position: fixed 相容方案</title>
<style type="text/css">
* { padding: 0; margin: 0; }
#content {
height: 5000px;
width: 50%;
border-right: 10px dotted red;
}
#demo_t, #demo_b, #demo_l, #demo_r {
background: #f90;
position: fixed;
}
#demo_t, #demo_b { left: 0; width: 100%; }
#demo_l, #demo_r { width: 50px; top: 300px; }
#demo_t { top: 0; }
#demo_b { bottom: 0; }
#demo_l { left: 0; }
#demo_r { right: 0; }
</style>
<!--[if lte IE 6]>
<style type="text/css">
html {
/* 這一行讓 IE6 滾動時不會抖動 */
background: url(about:black) no-repeat fixed;
}
#demo_t, #demo_b, #demo_l, #demo_r {
position: absolute;
}
#demo_t, #demo_b {
/* 解決 body 有 padding 時,IE6 下 100% 鋪不滿的問題 */
width: expression(offsetParent.clientWidth);
}
/* 以下三組規則用於 IE6 的 top 計算 */
#demo_l, #demo_r {
top: expression(offsetParent.scrollTop + 300);
}
#demo_t {
top: expression(offsetParent.scrollTop);
}
#demo_b {
top: expression(offsetParent.scrollTop + offsetParent.clientHeight - offsetHeight);
}
</style>
<![endif]-->
</head>
<body>
<div id="demo_t">上方固定區</div>
<div id="demo_b">下方固定區</div>
<div id="demo_l">左側固定區</div>
<div id="demo_r">右側固定區</div>
<div id="content"></div>
</body>
</html>
第一,background: url(about:black) no-repeat fixed。給 html 一個 fixed 背景的圖,可以強迫 IE6 進入某種渲染路徑,消除滾動時的抖動,這是這個方案的核心。
第二,用 expression(offsetParent.scrollTop) 把滾動量即時加回 top,模擬出固定定位的效果。IE6 只能把 fixed 當成 absolute,所以要用運算式補上滾動位移。
第三,寬度用 expression(offsetParent.clientWidth) 計算,避免 body 有 padding 時 100% 鋪不滿。
請把条件注释內的樣式抽到獨立的 CSS 檔案,用 <link> 引入。這樣其他瀏覽器完全不必下載這段代碼,能省下可觀流量。
最後必須誠實說明:CSS expression 效能極差,每次重繪都會重新執行運算式,且它本身就是 IE 曾出現大量安全漏洞的來源之一。這套方案今天只剩歷史與維護價值——IE6 的市場佔有率早已趨近於零,新專案不需要為此付出任何成本。若真的還在維護舊系統,把該段樣式隔離在条件注释中、不影響現代瀏覽器,就是最務實的處理。