萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> CMS 教學

IE6 不支持 position:fixed 完美解決方案(CSS Expression 實現固定定位)

問題背景

CSS position:fixed 可讓元素固定在視口位置(如右下角「回頂部」按鈕),不隨滾動條移動。但 IE6 僅支持 position:absolute,導致固定定位失效。

標準瀏覽器寫法

#top {
    position: fixed;
    bottom: 0;
    right: 20px;
}

IE6 兼容寫法(CSS Hack + Expression)

#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: absoluteIE6 專用,將 fixed 模擬為 absolute
_bottom: auto取消 bottom 定位,改用 top 計算
_top: expression(...)動態計算元素距離頁面頂部的像素值,實現「固定在視口底部」效果

Expression 計算邏輯:

  • document.documentElement.scrollTop:頁面垂直滾動距離。
  • document.documentElement.clientHeight:視口可見高度。
  • this.offsetHeight:元素自身高度。
  • 減去 margin-top/bottom,確保精準貼底。

副作用與優化

  • 性能:CSS Expression 在頁面每次重繪/滾動時都會重新計算,可能導致 IE6 CPU 佔用率飆升、頁面卡頓。
  • 優化方案:使用 JavaScript 監聽 window.onscroll 並手動設置 element.style.top,配合 setTimeout 節流,性能遠優於 Expression。
  • 現代建議:2024 年已無需兼容 IE6,建議直接使用 position:fixed 或 position:sticky,並通過優雅降級讓 IE6 用戶看到靜態定位元素。

JavaScript 替代方案(推薦用於維護老項目)

<!--[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 性能問題。

copyright © 萬盛學電腦網 all rights reserved