終於抽空再出一篇教學。今天教大家一個常用效果——固定居中。嚴格說這不算 JS 教程範疇,因為 FF、IE6 以上瀏覽器都支援 fixed 屬性,唯獨 IE6 不支援,因此特別為 IE6 寫一篇。而且這種效果也能鍛鍊大家的計算能力,以後很多效果都用得上。
固定居中或固定在其他位置,思路幾乎一樣,只要算法清楚,效果寫起來就輕而易舉。先貼程式碼:
<!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" />
<style>
body,div{padding:0px;margin:0px;}
#gd{width:100px;height:100px;background:#F00;color:#FFF;}
</style>
<script>
window.onload = function(){
var isIE=!!window.ActiveXObject;
var isIE6=isIE&&!window.XMLHttpRequest;
var t = (document.documentElement.clientHeight - document.getElementById("gd").offsetHeight)/2 + document.documentElement.scrollTop;
var l = (document.documentElement.clientWidth - document.getElementById("gd").offsetWidth)/2 + document.documentElement.scrollLeft;
if(isIE6){
setInterval(function(){
t = (document.documentElement.clientHeight - document.getElementById("gd").offsetHeight)/2 + document.documentElement.scrollTop;
l = (document.documentElement.clientWidth - document.getElementById("gd").offsetWidth)/2 + document.documentElement.scrollLeft;
document.getElementById("gd").style.position = "absolute"
document.getElementById("gd").style.top = t + "px";
document.getElementById("gd").style.left = l + "px";
},1)
}
else{
document.getElementById("gd").style.position = "fixed"
document.getElementById("gd").style.top = t + "px";
document.getElementById("gd").style.left = l + "px";
}
}
</script>
<title>固定居中</title>
</head>
<body>
<div id="gd">
我就在中間隨便你們怎麼改變窗口大小和高度
</div>
<div style="height:1200px;">
</div>
</body>
</html>
var isIE=!!window.ActiveXObject; var isIE6=isIE&&!window.XMLHttpRequest; 這兩句是判斷瀏覽器,是 Ajax 中常用的方法。
var t = (document.documentElement.clientHeight - document.getElementById("gd").offsetHeight)/2 + document.documentElement.scrollTop;
var l = (document.documentElement.clientWidth - document.getElementById("gd").offsetWidth)/2 + document.documentElement.scrollLeft;
這兩句是重點:document.documentElement.clientHeight 取得視窗高度;offsetHeight 取得元素實際高度;scrollTop 取得捲動條捲動的高度。視窗高度一半減去元素高度一半,就是元素居中距視窗頂部的 top 距離;由於內容較高時會出現捲動條,再加上 scrollTop 即為即時居中所需的 top 距離(left 算法相同)。
接著只需在捲動時即時把捲動高度加進去,並把即時的 t、l 設給元素的 top 與 left,就能製造「固定」的假象。
if(isIE6){ setInterval(function(){ ... },1) }:當是 IE6 時,用 setInterval 每 1 毫秒更新一次 t、l 並賦給元素的 top、left。1 毫秒極快,使用者拉捲動條不可能只花 1 毫秒,因此看不出破綻。也可用 window.onscroll 事件,但我覺得前者更好。
非 IE6 瀏覽器都支援 fixed,直接執行:position="fixed",並初始化設定居中的 t、l 值即可。
這裡只是居中,其他如固定底部、固定居左等道理相同,只是 top 與 left 的計算不同。setInterval 與 setTimeout 這兩個方法以後會經常用到。