方案一:精確控制三種狀態 (推薦)
(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 值