側邊欄隨頁面捲動,當捲動到特定位置時固定在視窗頂部 (或指定偏移),捲回頂部時恢復原位。常用於電商分類導航、購物車摘要、文章目錄等。
offset().top。$(window).scroll()。scrollTop() > offset.top 時,添加 .fixed class (CSS position:fixed; top:20px;)。<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>
當側邊欄捲動到頁尾時,改為 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>
現代瀏覽器 (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 不支援。| 方案 | 優點 | 缺點 | 適用 |
|---|---|---|---|
| JS scroll + fixed | 全瀏覽器支援、邏輯可控、支援複雜邊界(footer) | 需監聽 scroll、可能卡頓、需計算尺寸 | 需支援 IE、複雜邊界條件 |
| CSS position:sticky | 零 JS、效能極佳、原生平滑 | IE 不支援、邊界控制有限(無 footer 停止) | 現代專案、簡單固定需求 |