做過網站的人大概都遇過這個尷尬:頁面內容很少,頁尾就孤零零地浮在半空中,下面留一大塊空白;內容一多,它又乖乖待在最後面。理想的行為其實只有兩種——不夠長時貼住視窗底部,夠長時跟在內容後面。以下這個做法在 IE6、IE7、Firefox 等環境都測試過,縮放視窗也不會跑掉。
核心邏輯很直觀:把主要內容區與頁尾的高度加起來,跟瀏覽器可視高度比一比。如果總高度還不到一屏,就把頁尾改成絕對定位並貼到底;如果超過一屏,就把定位樣式清空,讓它回到正常的文件流裡。
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();
最後那個 setTimeout 是關鍵:它讓這段判斷每 10 毫秒重跑一次,使用者拉動視窗大小或內容動態改變時,頁尾位置都能跟著修正。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>頁尾貼底示例</title>
<style>
*{ margin:0; padding:0}
#info{background:#33CCFF}
#bottom{background:#FFCC00;width:100%;}
</style>
</head>
<body>
<div id="info">
2<br />2<br />2<br />2<br />2<br /><br />2<br />2<br />2<br />2<br />2<br /><br />2<br />20000</div>
<div id="bottom">bottom</div>
<script type="text/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();
</script>
</body>
</html>
把 #info 裡的內容多複製幾行,頁尾就會自動從「貼底」切換成「接在內容後面」;刪掉幾行再試一次,它又會回到視窗底部。這正是多數內容頁與列表頁都需要的行為。