如何在 JavaScript 中獲取瀏覽器視窗的內部高度和內部寬度?


在本文中,我們將學習如何使用 JavaScript 獲取瀏覽器視窗的內部高度和內部寬度。

JavaScript 定義了 window 物件的方法和屬性。這些屬性包括內部高度和內部寬度,可以幫助我們計算視窗內容區域的高度和寬度。

有兩種方法可以計算視窗的內部高度和內部寬度。

  • 使用 innerHeightinnerWidth 屬性 - 為了獲取內部高度內部寬度,JavaScript 提供了一些屬性,例如 window.innerHeight window.innerWidth。使用這些屬性,可以輕鬆找到瀏覽器視窗的高度和寬度。讓我們分別討論它們。

  • 使用 clientHeightclientWidth 屬性 - 同樣,Element.clientHeightElement.clientWidth 屬性分別返回當前元素的內部高度和寬度(以畫素為單位)。如果元素沒有任何 CSS,則這些屬性的值為0

語法

內部高度屬性用於計算視窗內容區域的高度。內部高度屬性的語法如下:

window.innerHeight or document.documentElement.clientHeight

內部寬度屬性用於計算視窗內容區域的高度。內部寬度屬性的語法如下:

Window.innerWidth or document.documentElement.clientWidth

示例 1

以下示例使用 window 物件的innerHeightinnerWidth 屬性返回視窗的高度和寬度。

<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 物件的clientHeightclientWidth 屬性返回視窗的高度和寬度。

<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>

執行以上程式碼後,將生成以下輸出。

更新於: 2022-12-08

494 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.