在做響應式設計或彈窗定位時,取得瀏覽器視窗的實際寬高經常派上用場。本文分享一個能相容不同瀏覽器的函式,可正確取得視窗的實際寬度與高度,並附完整可運行範例。
核心函式:
function getPageSize() {
var re = {};
if (document.documentElement && document.documentElement.clientHeight) {
var doc = document.documentElement;
re.width = (doc.clientWidth > doc.scrollWidth) ? doc.clientWidth - 1 : doc.scrollWidth;
re.height = (doc.clientHeight > doc.scrollHeight) ? doc.clientHeight : doc.scrollHeight;
} else {
var doc = document.body;
re.width = (window.innerWidth > doc.scrollWidth) ? window.innerWidth : doc.scrollWidth;
re.height = (window.innerHeight > doc.scrollHeight) ? window.innerHeight : doc.scrollHeight;
}
return re;
}
完整可運行範例:
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>獲取窗口大小</title>
<script type="text/javascript">
function getPageSize() {
var re = {};
if (document.documentElement && document.documentElement.clientHeight) {
var doc = document.documentElement;
re.width = (doc.clientWidth > doc.scrollWidth) ? doc.clientWidth - 1 : doc.scrollWidth;
re.height = (doc.clientHeight > doc.scrollHeight) ? doc.clientHeight : doc.scrollHeight;
} else {
var doc = document.body;
re.width = (window.innerWidth > doc.scrollWidth) ? window.innerWidth : doc.scrollWidth;
re.height = (window.innerHeight > doc.scrollHeight) ? window.innerHeight : doc.scrollHeight;
}
document.form1.availHeight.value = re.width;
document.form1.availWidth.value = re.height;
return re;
}
</script>
</head>
<body>
<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">
getPageSize();
window.onresize = getPageSize;
</script>
</body>
</html>
函式先判斷 document.documentElement 是否可用(用以區分標準模式與舊版 quirks 模式),再取 clientWidth/clientHeight 與 scrollWidth/scrollHeight 中的較大值作為實際尺寸。最後透過 window.onresize 讓視窗改變大小時也能即時更新數值。