內容不超過一屏時,頁腳該乖乖待在瀏覽器視窗底部;內容超過一屏時,它則跟在內容後面、也就是網頁的最下方。以下示範一種用 JavaScript 判斷並切換的寫法。
當視窗變小、內容仍不足一屏時,頁腳會跟著視窗底部移動,不會浮在半空中;一旦內容多於一屏,頁腳就回到文件流中,顯示在網頁最下方。這個做法在 IE6、IE7、Firefox 上都能正常運作,縮放視窗也不會出問題。
function positionFooter() {
var info = document.getElementById("info");
var bottom = document.getElementById("bottom");
var infoHeight = info.scrollHeight;
var bottomHeight = bottom.scrollHeight;
var allHeight = document.documentElement.clientHeight;
if ((infoHeight + bottomHeight) < allHeight) {
bottom.style.position = "absolute";
bottom.style.bottom = "0";
} else {
bottom.style.position = "";
bottom.style.bottom = "";
}
setTimeout(positionFooter, 10);
}
positionFooter();
邏輯很單純:把內容區高度加上頁腳高度,跟視窗可見高度相比。若總和比較小,就讓頁腳改為絕對定位貼齊視窗底部;否則還原成一般的文件流定位。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>頁腳保持在頁面底部</title>
<style>
* { margin: 0; padding: 0; }
#info { background: #33CCFF; }
#bottom { background: #FFCC00; width: 100%; }
</style>
</head>
<body>
<div id="info">這裡放主內容</div>
<div id="bottom">bottom</div>
<script>
function positionFooter() {
var info = document.getElementById("info");
var bottom = document.getElementById("bottom");
if ((info.scrollHeight + bottom.scrollHeight) <
document.documentElement.clientHeight) {
bottom.style.position = "absolute";
bottom.style.bottom = "0";
} else {
bottom.style.position = "";
bottom.style.bottom = "";
}
setTimeout(positionFooter, 10);
}
positionFooter();
</script>
</body>
</html>
輪詢改成事件觸發。用 setTimeout 每 10 毫秒執行一次,會持續佔用資源。改用 window.addEventListener("resize", positionFooter) 搭配首次呼叫即可,效果相同而負擔小得多。
這個需求現在有純 CSS 解法。利用 flex 讓頁腳自動被推到底部,不需要任何 JavaScript:
body {
min-height: 100vh;
display: flex;
flex-direction: column;
}
main { flex: 1; } /* 內容區自動撐開剩餘空間 */
footer { flex: none; }
當內容不足一屏時,main 的 flex: 1 會把頁腳推到視窗底部;內容超過一屏時,頁腳自然跟在內容之後。程式碼更少、效能更好,也不受視窗縮放影響,建議優先採用。