頁面側邊懸浮元素(廣告/客服/回頂部)隨頁面滾動平滑跟隨,而非生硬固定或瞬移。
<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 實現平滑跟隨。position: fixed; top: 18px; right: 20px; 即可,無需 JS。#float-ad {
position: fixed; /* 相對視口固定 */
right: 20px; top: 100px;
z-index: 9999;
transition: transform .3s ease; /* 若需動畫進場 */
}
現代瀏覽器 position: fixed 效能極佳,無需 JS 計算,優先採用;僅在需「延遲跟隨」視覺效果時使用 JS 緩動。