單純讓側欄固定雖然方便,但若頁尾有頁腳,固定元素會蓋在頁腳上面。解法是在接近頁尾時把定位方式從 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 的算法是「文件總高 − 已捲動距離 − 元素自身高度」,代表該元素底部還剩多少空間。當這個值大於頁腳高度時,還有餘裕,可以維持 fixed;一旦小於或等於頁腳高度,就換成 absolute,讓它停在原本的位置上不再覆蓋頁腳。若還沒捲過元素原位,則兩種特殊定位都不套用,回到正常的文件流。
absolute 是相對於最近的已定位祖先元素,因此必須在 widget 的父層加上 position: relative,否則它會相對整個頁面定位,位置完全跑掉:
.widget-wrap { position: relative; }
這套邏輯用 position: sticky 加上適當的容器就能大幅簡化,不必監聽 scroll:
.widget-wrap { position: relative; }
#widget { position: sticky; top: 20px; }
sticky 會自動在容器範圍內保持黏著,到達容器底緣就自然停下,正好對應這裡要的效果。若仍需相容舊版瀏覽器,再沿用上述 jQuery 切換 class 的寫法作為退路即可。