如何在 JavaScript 中獲取瀏覽器視窗的內部高度和內部寬度?
在本文中,我們將學習如何使用 JavaScript 獲取瀏覽器視窗的內部高度和內部寬度。
JavaScript 定義了 window 物件的方法和屬性。這些屬性包括內部高度和內部寬度,可以幫助我們計算視窗內容區域的高度和寬度。
有兩種方法可以計算視窗的內部高度和內部寬度。
使用 innerHeight 和 innerWidth 屬性 - 為了獲取內部高度和內部寬度,JavaScript 提供了一些屬性,例如 window.innerHeight和 window.innerWidth。使用這些屬性,可以輕鬆找到瀏覽器視窗的高度和寬度。讓我們分別討論它們。
使用 clientHeight 和 clientWidth 屬性 - 同樣,Element.clientHeight 和 Element.clientWidth 屬性分別返回當前元素的內部高度和寬度(以畫素為單位)。如果元素沒有任何 CSS,則這些屬性的值為0。
語法
內部高度屬性用於計算視窗內容區域的高度。內部高度屬性的語法如下:
window.innerHeight or document.documentElement.clientHeight
內部寬度屬性用於計算視窗內容區域的高度。內部寬度屬性的語法如下:
Window.innerWidth or document.documentElement.clientWidth
示例 1
以下示例使用 window 物件的innerHeight 和innerWidth 屬性返回視窗的高度和寬度。
<html>
<head>
<title>To calculate Inner Height and Inner Width of a window</title>
</head>
<body>
<p id="text1"></p>
<button onclick="calculateHeight()">Click Here</button>
<p id="text2"></p>
<script>
text1.innerHTML = "Click the below button to calculate Height of a window";
function calculateHeightAndWidth(){
var height = window.innerHeight;
var width = window.innerWidth;
text2.innerHTML = " Height : "+height+" pixels"+" Width: "+width+" pixels";
}
</script>
</body>
</html>
執行以上程式碼後,將生成以下輸出。
示例 2
以下示例使用 window 物件的clientHeight 和clientWidth 屬性返回視窗的高度和寬度。
<html>
<head>
<title>To calculate Inner Height and Inner Width of a window</title>
</head>
<body>
<p id="text1"></p>
<button onclick="calculateHeight()">Click Here</button>
<p id="text2"></p>
<script>
text1.innerHTML = "Click the below button to calculate Height of a window";
function calculateHeightAndWidth(){
var height = document.documentElement.clientHeight;
var width = document.documentElement.clientWidth;
text2.innerHTML = " Height : "+height+" pixels"+" Width: "+width+" pixels";
}
</script>
</body>
</html>
執行以上程式碼後,將生成以下輸出。
示例 3
以下示例使用document.body.clientHeight/Width計算視窗的高度和寬度。以上示例和以下示例的區別在於,document.documentElement 獲取 html 元素,而document.body 獲取 body 元素。
<html>
<head>
<title>To calculate Inner Height and Inner Width of a window</title>
</head>
<body>
<p id="text1"></p>
<button onclick="calculateHeight()">Click Here</button>
<p id="text2"></p>
<script>
text1.innerHTML = "Click the below button to calculate Height of a window";
function calculateHeightAndWidth(){
var height = document.body.clientHeight;
var width = document.body.clientWidth;
text2.innerHTML = " Height : "+height+" pixels"+" Width: "+width+" pixels";
}
</script>
</body>
</html>
執行以上程式碼後,將生成以下輸出。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP