萬盛學電腦網

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

jQuery 實現滾動固定(Sticky)元素:從基礎版到錨點修正的完整方案

「隨頁面滾動始終顯示」的導航欄、側邊欄、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'
      });
    }
  }
});

HTML 結構範例

<div class="header">...</div>
<div id="scroller_anchor"></div> <!-- 錨點:零高度,不佔空間 -->
<div class="scroller">
  <nav class="sub-nav">...</nav>
</div>
<div class="content">...動態載入內容...</div>

現代化替代方案:CSS `position: sticky`

現代瀏覽器(含移動端)已全面支援,無需 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;
}
  • ✅ 無 JS 依賴,無滾動事件監聽器性能開銷
  • ✅ 自動處理動態佈局變化(瀏覽器原生計算)
  • ✅ 支援 `top`/`bottom`/`left`/`right` 多邊吸附
  • ⚠️ 父元素 `overflow: hidden/auto/scroll` 會導致失效 → 確保祖先鏈無截斷滾動容器
  • ⚠️ IE 全系列不支援 → 需 Polyfill(如 `stickyfill`)或降級為 JS 方案

進階增強:平滑過渡、邊界檢測、多元素協同

1. 狀態切換動畫

CSS `transition` 僅對 `box-shadow`/`background`/`transform` 生效,`position` 切換無動畫。如需平滑,可用 `transform: translateY(-100%)` 隱藏 → `translateY(0)` 顯示,配合 `will-change: transform`。

2. 頁腳邊界檢測(防止遮擋 Footer)

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'
  });
}

3. 多 Sticky 元素協同(如:頂部導航 + 側邊欄雙固定)

各自獨立計算錨點,互不干擾。側邊欄常用 `position: sticky; top: 80px;`(避開頂部導航高度)。

無障礙與 SEO 考量

  • 固定元素不應遮擋頁面主內容(尤其是鍵盤焦點元素),需設置 `padding-top` 或 `scroll-padding-top`。
  • 語義化:`
  • 避免 `position: fixed` 導致頁面內錨點跳轉偏移(目標被固定頭部遮擋),CSS `scroll-margin-top: 60px` 修正。

結語:選對工具,少寫代碼,少造 Bug

現代項目首選 `position: sticky` + 降級策略;必須兼容 IE/舊瀏覽器時,使用錨點修正版 JS 方案。核心原理只有一句:**用一個不變的參考點,校準一個會變的狀態邊界**。

copyright © 萬盛學電腦網 all rights reserved