DIV CSS 佈局教程網

解讀 JS 取得瀏覽器視窗尺寸的程式碼
編輯:關於JavaScript     

本節程式碼主要用到 Document 物件與視窗相關的一些屬性,先把功能釐清:

要取得視窗尺寸,不同瀏覽器需要採用不同的屬性與方法。若想得到視窗的真實大小,在 Netscape 系(含 Firefox 等)需要使用 Window 的屬性;在 IE 下則得深入 Document 內部,對 body 進行檢測;而在 DOM 標準環境下,要注意的是根元素 <html> 的尺寸,而非 <body> 元素。

具體來說:Window 的 innerWidth 包含當前視窗的內部寬度,innerHeight 則是內部高度。Document 的 body 屬性對應 HTML 文件的 <body> 標籤,documentElement 則代表根節點。document.body.clientHeight 與 document.body.clientWidth 分別表示文件所在視窗的當前高度與寬度。

程式碼

<!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>
<title>請調整瀏覽器視窗</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<h2 align="center">請調整瀏覽器視窗大小</h2><hr>
<form action="#" method="get" name="form1" id="form1">
<!--顯示瀏覽器視窗的實際尺寸-->
瀏覽器視窗 的實際高度: <input type="text" name="availHeight" size="4"><br>
瀏覽器視窗 的實際寬度: <input type="text" name="availWidth" size="4"><br>
</form>
<script type="text/javascript">
<!--
var winWidth = 0;
var winHeight = 0;
function findDimensions() //函數:獲取尺寸
{
//獲取視窗寬度
if (window.innerWidth)
winWidth = window.innerWidth;
else if ((document.body) && (document.body.clientWidth))
winWidth = document.body.clientWidth;
//獲取視窗高度
if (window.innerHeight)
winHeight = window.innerHeight;
else if ((document.body) && (document.body.clientHeight))
winHeight = document.body.clientHeight;
//通過深入Document內部對body進行檢測,獲取視窗大小
if (document.documentElement && document.documentElement.clientHeight &&
document.documentElement.clientWidth)
{
winHeight = document.documentElement.clientHeight;
winWidth = document.documentElement.clientWidth;
}
//結果輸出至兩個文本框
document.form1.availHeight.value= winHeight;
document.form1.availWidth.value= winWidth;
}
findDimensions(); //調用函數,獲取數值
window.onresize=findDimensions;
//-->
</script>
</body>
</html>

源程序解讀

(1)程式碼先建立一個表單,內含兩個文字框,用來顯示視窗的寬與高,且數值會隨視窗尺寸變化而更新。

(2)接著在 JavaScript 中宣告 winWidth 與 winHeight 兩個變數,分別保存寬度與高度。

(3)在 findDimensions() 函式中,先用 window.innerWidth 與 window.innerHeight 取得尺寸並存入變數。

(4)再深入 Document 內部檢測 body 與 documentElement,取得更精確的視窗大小並覆寫前述變數。

(5)函式最後透過名稱存取表單元素,把結果寫進兩個文字框。

(6)最後呼叫 findDimensions() 完成初始化,並透過 window.onresize 讓數值在視窗縮放時即時更新。

執行後頁面上會出現兩個文字框,顯示視窗目前的寬與高;當你拖動邊界調整視窗大小時,框內數值也會同步改變。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved