CSS position:fixed 可讓元素固定在視口位置(如右下角「回頂部」按鈕),不隨滾動條移動。但 IE6 僅支持 position:absolute,導致固定定位失效。
#top {
position: fixed;
bottom: 0;
right: 20px;
}
#top {
position: fixed; /* 現代瀏覽器 */
_position: absolute; /* IE6 識別的 Hack(下劃線前綴) */
bottom: 0;
right: 20px;
_bottom: auto; /* IE6 重置 bottom */
_top: expression(
eval(
document.documentElement.scrollTop +
document.documentElement.clientHeight -
this.offsetHeight -
(parseInt(this.currentStyle.marginTop, 10) || 0) -
(parseInt(this.currentStyle.marginBottom, 10) || 0)
)
);
}
| 屬性 | 作用 |
|---|---|
_position: absolute | IE6 專用,將 fixed 模擬為 absolute |
_bottom: auto | 取消 bottom 定位,改用 top 計算 |
_top: expression(...) | 動態計算元素距離頁面頂部的像素值,實現「固定在視口底部」效果 |
Expression 計算邏輯:
document.documentElement.scrollTop:頁面垂直滾動距離。document.documentElement.clientHeight:視口可見高度。this.offsetHeight:元素自身高度。window.onscroll 並手動設置 element.style.top,配合 setTimeout 節流,性能遠優於 Expression。position:fixed 或 position:sticky,並通過優雅降級讓 IE6 用戶看到靜態定位元素。<!--[if lte IE 6]>
<script>
(function() {
var el = document.getElementById('top');
if (!el) return;
function setTop() {
var scrollTop = document.documentElement.scrollTop;
var clientHeight = document.documentElement.clientHeight;
el.style.top = (scrollTop + clientHeight - el.offsetHeight) + 'px';
}
window.attachEvent('onscroll', setTop);
window.attachEvent('onresize', setTop);
setTop();
})();
</script>
<![endif]-->
將以上代碼放在頁面底部,僅 IE6 執行,無 Expression 性能問題。