JavaScript >> Javascript 文檔 >  >> JavaScript

如何使用 JavaScript 獲取窗口的寬度和高度

要獲取瀏覽器窗口的寬度和高度,可以使用 innerWidthinnerHeight window 的屬性 對象。

innerWidthinnerHeight 屬性返回窗口內容區域的寬度和高度。

這是一個例子:

const width = window.innerWidth;
const height = window.innerHeight;

上述解決方案適用於所有現代瀏覽器,以及 IE9 及更高版本。

要支持 IE8 及更早版本(真的嗎?),您可以使用 clientWidthclientHeight 屬性也是:

const width = window.innerWidth ||
    document.documentElement.clientWidth ||
    document.body.clientWidth;

const height = window.innerHeight ||
    document.documentElement.clientHeight ||
    document.body.clientHeight;

ES11 globalThis

ECMAScript 2020 (ES11) 引入了 globalThis 引用全局 this 的變量 代碼運行的上下文。

例如,在網絡瀏覽器中,globalThisthis 在 Node.js 應用程序中,globalThis 將是 global .

您可以使用 globalThis 獲取窗口內容區域和外部區域的寬度和高度:

// content area
const width = globalThis.innerWidth;
const height = globalThis.innerHeight;

// outer area
const width = globalThis.outerWidth;
const height = globalThis.outerHeight;

Tutorial JavaScript 教程
  1. 使用 append() 附加大塊 html

  2. 私有區塊​​鏈:Hyperledger Composer Javascript API

  3. 使用 Chart.js 以很酷的方式顯示民意調查數據

  4. Vue 有什麼特點?

  5. 在 Vue 中使用 Bootstrap 4

  6. 在 JavaScript 中獲取客戶端的時區(和偏移量)

  7. 動態呈現的 React 組件不會在父狀態更改時重新呈現

  1. 使用 Apollo 介紹 GraphQL

  2. 按路徑生產 - 新的 JavaScript 設計模式

  3. Ember 3.23 發布

  4. Google oauth 2.0 API 密碼更改用戶名和密碼不被接受

  5. 🎃🦇 HTMLoween 🦇🎃 - HTML、JS 和 CSS 讓你熱血沸騰! 😱

  6. 一年的大規模 GraphQL - 最大的收穫

  7. 介紹 react-tweenful:React 的動畫引擎

  1. 我為什麼要上鉤?

  2. 使用 Visual Studio Code 在 TypeScript 中調試 Node.js 應用程序

  3. 用於快速 PWA 開發的全棧解決方案!

  4. [第 1 部分] 處理應用程序錯誤的主動方法