萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現側邊欄跟隨捲動固定(Sticky Sidebar)

效果描述

側邊欄隨頁面捲動,當捲動到特定位置時固定在視窗頂部 (或指定偏移),捲回頂部時恢復原位。常用於電商分類導航、購物車摘要、文章目錄等。

核心邏輯

  1. 記錄側邊欄初始位置 offset().top。
  2. 監聽 $(window).scroll()。
  3. 當 scrollTop() > offset.top 時,添加 .fixed class (CSS position:fixed; top:20px;)。
  4. 反之移除 class 恢復靜態定位。

完整實作代碼

<style>
#sidebar {
  width: 260px;
  float: right;
  transition: top 0.2s; /* 平滑過渡 */
}
#sidebar.fixed {
  position: fixed;
  top: 20px; /* 距離視窗頂部 20px */
  /* 固定寬度防止塌陷 */
  width: 260px;
}
/* IE6 相容 (如需) */
* html #sidebar.fixed {
  position: absolute;
  top: expression(20 + (document.documentElement.scrollTop || document.body.scrollTop) + 'px');
}
</style>

<div id="main">主內容區...</div>
<div id="sidebar">側邊欄內容</div>

<script src="jquery.min.js"></script>
<script>
$(function() {
  var $sidebar = $('#sidebar');
  var offset = $sidebar.offset();

  $(window).scroll(function() {
    var scrollTop = $(window).scrollTop();
    
    if (scrollTop > offset.top) {
      $sidebar.addClass('fixed');
    } else {
      $sidebar.removeClass('fixed');
    }
  });
});
</script>

進階:防止遮擋 Footer (底部停止)

當側邊欄捲動到頁尾時,改為 position:absolute 固定在底部上方,避免覆蓋 Footer。

$(function() {
  var $sidebar = $('#sidebar');
  var $footer = $('#footer');
  var offset = $sidebar.offset();
  var sidebarHeight = $sidebar.outerHeight();

  $(window).scroll(function() {
    var scrollTop = $(window).scrollTop();
    var windowHeight = $(window).height();
    var docHeight = $(document).height();
    
    // 側邊欄底部距離文件底部的距離
    var sidebarBottom = scrollTop + windowHeight - offset.top;
    var footerTop = $footer.offset().top;
    
    if (scrollTop > offset.top) {
      // 檢查是否碰到 footer
      if (scrollTop + sidebarHeight > footerTop) {
        $sidebar.removeClass('fixed').addClass('absolute-bottom')
                .css({ top: footerTop - sidebarHeight - offset.top });
      } else {
        $sidebar.removeClass('absolute-bottom').addClass('fixed')
                .css({ top: 20 });
      }
    } else {
      $sidebar.removeClass('fixed absolute-bottom').css({ top: 0 });
    }
  });
});
<style>
#sidebar.absolute-bottom {
  position: absolute;
  top: auto; /* 由 JS 計算設定 */
  bottom: 0;
}
</style>

現代替代方案:CSS position: sticky

現代瀏覽器 (IE 除外) 支援純 CSS 實現,零 JS、效能最佳:

#sidebar {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 20px;
  align-self: flex-start; /* 若在 Flex 容器中 */
  /* 必須指定高度或 max-height 避免內容超出容器 */
  max-height: calc(100vh - 40px);
  overflow-y: auto; /* 內容過長可滾動 */
}

瀏覽器支援

  • position: sticky:Chrome 56+、Firefox 32+、Safari 6.1+、Edge 16+、IE 不支援。
  • 需 Polyfill:Stickyfill 可讓 IE 支援。

選擇建議

方案優點缺點適用
JS scroll + fixed全瀏覽器支援、邏輯可控、支援複雜邊界(footer)需監聽 scroll、可能卡頓、需計算尺寸需支援 IE、複雜邊界條件
CSS position:sticky零 JS、效能極佳、原生平滑IE 不支援、邊界控制有限(無 footer 停止)現代專案、簡單固定需求
copyright © 萬盛學電腦網 all rights reserved