單純讓側邊欄固定很簡單,但頁尾常常會出現問題:固定的元素會蓋住頁腳內容。解法是在接近頁面底部時,把定位方式從 fixed 切換成 absolute,讓它隨著頁尾一起離開視窗。
<script type="text/javascript">
var rollSet = $('#widget');
var offset = rollSet.offset();
var fwidth = $("#footer").height();
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
// 該元素底部距離頁面底部的距離
var scrollBtm = $(document).height() - $(window).scrollTop() - $("#widget").height();
if (offset.top < scrollTop) {
if (scrollBtm > fwidth) {
rollSet.removeClass('absolute').addClass('fixed');
} else {
rollSet.removeClass('fixed').addClass('absolute');
}
} else {
rollSet.removeClass('fixed');
}
});
</script>
scrollBtm 的計算:頁面總高度 − 已捲動距離 − 元素自身高度 = 該元素底部到頁面底部的剩餘距離。
判斷分三個階段:
一、offset.top >= scrollTop(還沒捲到該元素)→ 移除 fixed,維持正常的文件流位置。
二、已捲過該元素,且 scrollBtm > fwidth(離頁尾還有一段距離)→ 加上 fixed,讓它固定在視窗上。
三、已捲過該元素,但 scrollBtm <= fwidth(逼近頁尾)→ 切換成 absolute,讓它停在頁尾之上,不會遮住頁腳。
使用時,CSS 需為絕對定位的父層加上 position:relative,否則 absolute 會以整個文件為基準,位置計算便會出錯。
範例中 rollSet 存的是 jQuery 物件,後面卻用 $("#widget").height() 重新查詢同一元素,顯得多餘。統一用同一個參照會更清楚:
$(function(){
var $widget = $('#widget'),
$footer = $('#footer');
function update(){
var st = $(window).scrollTop();
var wh = $(window).height();
var start = $widget.offset().top; // 開始固定的門檻
var limit = $footer.offset().top - $widget.outerHeight();
if (st <= start) {
$widget.removeClass('fixed');
} else if (st < limit) {
$widget.addClass('fixed');
} else {
$widget.removeClass('fixed').addClass('absolute');
}
}
$(window).on('scroll', update);
$(window).on('resize', update);
update();
});
這裡用 $footer.offset().top 直接取得頁尾的實際位置,比「總高度減去各種高度」的推算來得直覺,也不容易在元素高度變化時出錯。同時補上了 resize 與初始呼叫——視窗尺寸改變後不重算,是這類元件常見的疏漏。
這個需求用 CSS 就能完整解決,不必任何 JavaScript:
.sidebar {
position: -webkit-sticky;
position: sticky;
top: 20px;
}
position:sticky 天生就會在父容器的邊界內限制移動範圍——換言之,當容器(例如包含側邊欄與頁尾的外層 div)底邊抵達時,它會自動停下來。這正好就是上面那段 JS 想達成的效果,而且不需要計算任何座標、不受元素高度變化影響、效能也更好。
使用上只有兩個注意事項:父容器不可設 overflow:hidden 或 auto(會破壞 sticky 的參照),以及必須給一個 top 或 bottom 值。若你的情境還需要支援 IE11 以下的舊版瀏覽器,才需要回頭採用 JS 方案;否則 sticky 是明顯更優的選擇。