「隨頁面滾動始終顯示」的導航欄、側邊欄、CTA 按鈕是提升轉化率的常用模式。本文從原理到代碼,解決動態高度變化導致錨點失效的核心痛點,提供生產級可用方案。

目標元素(`.scroller`)初始 `position: relative`。當頁面滾動超過其原始頂部位置 → 切換為 `position: fixed; top: 0; margin-top: 0`;滾回原位置上方 → 還原 `relative`。
var scroller_anchor = jQuery('.scroller').offset().top;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() >= scroller_anchor
&& jQuery('.scroller').css('position') != 'fixed') {
jQuery('.scroller').css({
'position': 'fixed',
'margin-top': '0'
});
} else if (jQuery(this).scrollTop() < scroller_anchor
&& jQuery('.scroller').css('position') != 'relative') {
jQuery('.scroller').css({
'margin-top': '10px', // 原始 margin
'position': 'relative'
});
}
});
若 `.scroller` 上方存在動態增減高度的元素(如:AJAX 載入推薦模塊、展開/摺疊面板、廣告彈出),初始 `offset().top` 失效,導致固定觸發時機錯亂(過早/過晚/閃爍)。
在 `.scroller` 原始位置插入一個零高度錨點元素(`
`),實時讀取其 `offset().top` 作為基準,天然免疫上方佈局變化。jQuery(window).scroll(function() {
// 確保錨點存在(防止 SPA 路由切換後元素銷毀)
if (jQuery('#scroller_anchor').length > 0) {
var scroller_anchor = jQuery('#scroller_anchor').offset().top;
if (jQuery(this).scrollTop() >= scroller_anchor
&& jQuery('.scroller').css('position') != 'fixed') {
jQuery('.scroller').css({
'position': 'fixed',
'margin-top': '0',
'z-index': 999, // 確保層級
'width': '100%', // fixed 脫離文檔流需顯式寬度
'box-shadow': '0 2px 8px rgba(0,0,0,.08)' // 視覺分層
});
} else if (jQuery(this).scrollTop() < scroller_anchor
&& jQuery('.scroller').css('position') != 'relative') {
jQuery('.scroller').css({
'margin-top': '10px',
'position': 'relative',
'z-index': 'auto',
'width': 'auto',
'box-shadow': 'none'
});
}
}
});
<div class="header">...</div>
<div id="scroller_anchor"></div> <!-- 錨點:零高度,不佔空間 -->
<div class="scroller">
<nav class="sub-nav">...</nav>
</div>
<div class="content">...動態載入內容...</div>
現代瀏覽器(含移動端)已全面支援,無需 JS,性能更優、代碼更簡:
.scroller {
position: sticky;
top: 0;
z-index: 999;
background: white; /* 防止穿透 */
box-shadow: 0 2px 8px rgba(0,0,0,.08);
transition: box-shadow 0.2s ease;
}
CSS `transition` 僅對 `box-shadow`/`background`/`transform` 生效,`position` 切換無動畫。如需平滑,可用 `transform: translateY(-100%)` 隱藏 → `translateY(0)` 顯示,配合 `will-change: transform`。
var footerTop = jQuery('#footer').offset().top;
var scrollerHeight = jQuery('.scroller').outerHeight();
if (jQuery(window).scrollTop() + jQuery(window).height() > footerTop - scrollerHeight) {
// 即將遮擋 Footer,改為 absolute 定位在 Footer 上方
jQuery('.scroller').css({
'position': 'absolute',
'top': footerTop - scrollerHeight - 10,
'bottom': 'auto'
});
}
各自獨立計算錨點,互不干擾。側邊欄常用 `position: sticky; top: 80px;`(避開頂部導航高度)。
現代項目首選 `position: sticky` + 降級策略;必須兼容 IE/舊瀏覽器時,使用錨點修正版 JS 方案。核心原理只有一句:**用一個不變的參考點,校準一個會變的狀態邊界**。