當頁面內容不足一屏時,頁腳最好停在瀏覽器視窗底部;內容超過一屏時,則跟在內容後方。這可透過 JavaScript 偵測高度來切換。
先取得內容區與頁腳的高度,再取得視窗高度。若兩者總和小於視窗高度,就把頁腳設為絕對定位並貼底;否則恢復一般流式排版。
function test() {
var infoHeight = document.getElementById("info").scrollHeight;
var bottomHeight = document.getElementById("bottom").scrollHeight;
var allHeight = document.documentElement.clientHeight;
var bottom = document.getElementById("bottom");
if ((infoHeight + bottomHeight) < allHeight) {
bottom.style.position = "absolute";
bottom.style.bottom = "0";
} else {
bottom.style.position = "";
bottom.style.bottom = "";
}
setTimeout(function(){ test(); }, 10);
}
test();
這種做法能在舊版瀏覽器中運作,但會定時執行。現代專案也可改用 Flexbox 或 Grid 的 sticky footer 技巧,讓結構更單純。