萬盛學電腦網

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

JavaScript 實現懸浮廣告跟隨滾動條平滑移動

效果描述

頁面側邊懸浮元素(廣告/客服/回頂部)隨頁面滾動平滑跟隨,而非生硬固定或瞬移。

原始代碼重構(現代寫法)

<div id="float-ad" style="position: absolute; left: 800px; top: 18px; z-index: 9999;">
  <a href="https://example.com" target="_blank"><img src="ad.gif" alt="廣告"></a>
</div>

<script>
(function () {
  const el = document.getElementById('float-ad');
  if (!el) return;
  let lastScrollY = window.scrollY;
  const ease = 0.1; // 緩動係數 0~1,越小越平滑

  function tick() {
    const targetY = window.scrollY + 18; // 目標位置:視口頂部 + 18px
    const diff = targetY - el.offsetTop;
    if (Math.abs(diff) > 0.5) {
      el.style.top = (el.offsetTop + diff * ease) + 'px';
    }
    requestAnimationFrame(tick);
  }
  requestAnimationFrame(tick);
})();
</script>

關鍵改進點

  • 使用 requestAnimationFrame 替代 setInterval,效能更高、不阻塞主執行緒。
  • 緩動公式 current += (target - current) * ease 實現平滑跟隨。
  • 封裝為 IIFE 避免污染全域變數。
  • 若需固定於視口,直接用 position: fixed; top: 18px; right: 20px; 即可,無需 JS。

CSS 純樣式替代方案(推薦)

#float-ad {
  position: fixed; /* 相對視口固定 */
  right: 20px; top: 100px;
  z-index: 9999;
  transition: transform .3s ease; /* 若需動畫進場 */
}

現代瀏覽器 position: fixed 效能極佳,無需 JS 計算,優先採用;僅在需「延遲跟隨」視覺效果時使用 JS 緩動。

copyright © 萬盛學電腦網 all rights reserved