萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 監聽捲動事件固定元素位置:scrollTop 相容寫法與 CSS position:sticky 現代替代方案

傳統 JS 實作

<style>
#anchor {
  position: absolute; /* 必須為 absolute/fixed,top 才生效 */
  top: 40%;
  left: 40%;
  width: 100px;
  height: 100px;
  background: red;
}
</style>

<div id="anchor"></div>

<script>
const $anchor = $("#anchor");
let anchorTop = parseFloat($anchor.css("top")); // 解析 "40%" → 數值需換算
// 若 CSS 用 px 直接 parseInt 即可

window.onscroll = function () {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  $anchor.css("top", anchorTop + scrollTop + "px");
};
</script>

關鍵點解析

  • document.documentElement.scrollTop(標準模式)vs document.body.scrollTop(相容模式/舊瀏覽器),用 `||` 兼容。
  • 元素需設定 `position: absolute/fixed`,否則 `top` 無效。
  • 每次 scroll 觸發重排,大量元素時效能差,建議 節流。

優化:節流

function throttle(fn, delay) {
  let timer = null;
  return function (...args) {
    if (timer) return;
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
}

window.addEventListener("scroll", throttle(function () {
  const top = document.documentElement.scrollTop || document.body.scrollTop;
  $anchor.css("top", anchorTop + top + "px");
}, 16)); // ~60fps

現代最佳解法:CSS position: sticky

<style>
.sticky-box {
  position: sticky;
  top: 40%;       /* 相對視窗頂端距離 */
  left: 40%;
  width: 100px;
  height: 100px;
  background: red;
  z-index: 100;   /* 確保疊在內容上方 */
}
</style>

<div class="sticky-box"></div>

✅ **零 JS、零重排、瀏覽器原生最佳化**、支援 `top/right/bottom/left` 邊界吸附。

⚠️ 限制:

  • 祖先元素不可有 `overflow: hidden/auto/scroll`(會切斷 sticky 上下文)
  • IE 全版本不支援(可用 Stickyfill Polyfill)

IntersectionObserver 進階:動態吸頂/偵測可見性

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    entry.target.classList.toggle("is-stuck", entry.intersectionRatio < 1);
  });
}, { rootMargin: "-1px 0px 0px 0px" }); // 頂端觸頂觸發

observer.observe(document.querySelector(".sticky-box"));

總結

方案優點缺點適用場景
JS scroll + top完全控制、舊瀏覽器相容效能差、需節流、易抖動極舊專案維護
CSS sticky零 JS、效能最佳、語意清晰IE 不支援、受 overflow 限制現代專案首選
IntersectionObserver非同步、高效能、可偵測進出視窗API 較複雜需動態切換 sticky 狀態、懶加載

結論:能用 CSS sticky 就用 CSS sticky;必須 JS 時請加節流。

copyright © 萬盛學電腦網 all rights reserved