<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(相容模式/舊瀏覽器),用 `||` 兼容。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
<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` 邊界吸附。
⚠️ 限制:
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 時請加節流。