側邊欄跟隨捲動固定,但當捲動到頁尾 (Footer 區域) 時停止固定,改為絕對定位固定在 Footer 上方,避免遮擋頁腳內容。
scrollTop:目前捲動距離。offset.top:側邊欄原始頂部位置。scrollBtm = $(document).height() - scrollTop - $widget.height():側邊欄底部距離文件底部的距離。scrollBtm <= footerHeight 時,切換為 absolute 定位。<style>
#widget {
width: 300px;
background: #f5f5f5;
transition: top 0.2s;
}
#widget.fixed {
position: fixed;
top: 20px;
}
#widget.absolute {
position: absolute;
top: auto;
bottom: 0; /* 靠近 footer 上方 */
}
/* 父容器需 relative 定位 */
#mainContent { position: relative; }
</style>
<div id="mainContent">
<div id="widget">側邊欄內容</div>
<div id="main">主內容...很長...</div>
<div id="footer" style="height:300px; background:#333; color:#fff;">Footer 區域</div>
</div>
<script src="jquery.min.js"></script>
<script>
$(function() {
var $widget = $('#widget');
var $footer = $('#footer');
var offset = $widget.offset();
var footerHeight = $footer.outerHeight();
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
// 側邊欄底部距離文件底部距離
var scrollBtm = $(document).height() - scrollTop - $widget.outerHeight();
if (offset.top < scrollTop) {
// 已捲動超過側邊欄原始位置
if (scrollBtm > footerHeight) {
// 未到 footer 區域:固定定位
$widget.removeClass('absolute').addClass('fixed');
} else {
// 進入 footer 區域:絕對定位固定在 footer 上方
$widget.removeClass('fixed').addClass('absolute');
}
} else {
// 未捲動到側邊欄原始位置:靜態定位
$widget.removeClass('fixed absolute');
}
});
});
</script>
position:relative:絕對定位的側邊欄需相對父容器定位,否則會相對 body 導致位置錯誤。.absolute 類別設 bottom:0 而非 top,使其緊貼父容器底部 (即 Footer 上方)。outerHeight() 取得含邊框/內距的真實高度。| 情況 | 處理 |
|---|---|
| 側邊欄高度 > 視窗高度 | 固定時內容會被截斷。建議加 max-height: calc(100vh - 40px); overflow-y:auto; 內部捲動。 |
| Footer 高度動態變化 | 在 scroll 事件中即時取得 $footer.outerHeight() 或監聽 resize 更新。 |
| 多個固定元素 | 需計算疊加順序 (z-index) 與各自邊界,建議統一管理器協調。 |
| 水平捲動頁面 | 同理計算 scrollLeft 與右側邊界。 |
若不需支援 IE,可結合 position: sticky 與 max-height 實現基礎固定,但「Footer 停止」仍需 JS 計算切換為 absolute。