萬盛學電腦網

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

JavaScript 固定側邊欄跟隨滾動效果 (兩種方案對比)

方案一:精確控制三種狀態 (推薦)

(function ($) {
  var $fix = $('#div_right'),      // 浮動元素
      $main = $('.main'),          // 容器區塊
      fixTop = $fix.offset().top;  // 初始頂部位置

  $(window).scroll(function () {
    var scrollTop = $(this).scrollTop(),
        fixBottom = $fix.height() + scrollTop - 10,
        mainBottom = $main.offset().top + $main.height();

    if (scrollTop <= fixTop && fixBottom < mainBottom) {
      $fix.css({ position: 'static', top: -10 });
    } else if (scrollTop > fixTop && fixBottom < mainBottom) {
      $fix.css({ position: 'fixed', top: -10 });
    } else if (scrollTop > fixTop && fixBottom >= mainBottom) {
      var pos = mainBottom - fixBottom - 10;
      $fix.css({ position: 'fixed', top: pos });
    }
  });
})(jQuery);

方案二:簡易版 (固定觸發點)

$(window).bind('scroll', function () {
  var trigger = 1165; // 固定觸發高度
  if ($(document).scrollTop() > trigger) {
    $('#div_right').css({ position: 'fixed', top: '-10px', 'margin-top': 0 });
  } else {
    $('#div_right').css('position', '');
  }
});

適用情境比較

方案優點缺點適用場景
一精確貼底、不遮擋 footer、支援容器高度變動程式碼較多長頁面、側邊欄高度大於視窗
二極簡、易維護需手動調整 trigger、不自適應容器高度短頁面、固定版面

核心原理

  • 監聽 scroll 事件
  • 比較 scrollTop、元素高度、容器底部
  • 動態切換 static/fixed 並計算 top 值
copyright © 萬盛學電腦網 all rights reserved