萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 實現返回頂部按鈕固定右下角並相容 IE6 的寫法

需求

「回到頂部」按鈕固定於瀏覽器視窗右下角,且需支援 IE6(不支援 position: fixed)。

相容 IE6 的 CSS Hack

#goTop {
  position: fixed;           /* 現代瀏覽器 */
  right: 20px;
  bottom: 20px;
  z-index: 999;
  /* IE6 Hack */
  _position: absolute;
  _bottom: auto;
  _right: 50%;
  _margin-right: -536px;     /* 視版面寬度調整,使按鈕靠右 */
  _top: expression(
    eval(
      document.documentElement.scrollTop +
      document.documentElement.clientHeight -
      this.offsetHeight -
      (parseInt(this.currentStyle.marginTop, 10) || 0) -
      (parseInt(this.currentStyle.marginBottom, 10) || 0)
    )
  );
}

原理解析

  • 現代瀏覽器讀取 position: fixed,忽略底線 _ 屬性。
  • IE6 忽略 fixed,套用 _position: absolute 搭配 expression 動態計算 top,模擬 fixed 效果。
  • _right: 50% + _margin-right 負值,將元素推至視窗右側固定位置。

HTML 範例

<a id="goTop" href="#top" title="回到頂部">↑</a>

現代建議

IE6 市佔率已極低,新專案建議放棄 IE6 支援,直接使用 position: fixed 或 position: sticky(需 Polyfill),並搭配 Intersection Observer 實現滾動顯示/隱藏,效能更佳。

copyright © 萬盛學電腦網 all rights reserved