Window: innerWidth 屬性
只讀的 Window 屬性 innerWidth 以畫素為單位返回視窗的內部寬度(即視窗的 佈局視口 的寬度)。如果存在垂直捲軸,它也包含垂直捲軸的寬度。
類似地,可以使用 innerHeight 屬性來獲取視窗的內部高度(即佈局視口的高度)。此度量也考慮了水平捲軸的可見高度。
值
一個表示窗口布局視口寬度(以畫素為單位)的整數值。此屬性是隻讀的,沒有預設值。
要更改視窗的寬度,請使用 Window 的視窗大小調整方法之一,例如 resizeBy() 或 resizeTo()。
用法說明
如果您需要獲取視窗寬度(不包括捲軸和邊框),請改用根 <html> 元素的 clientWidth 屬性。
innerWidth 屬性可用於任何視窗或表現得像視窗的物件,例如框架或標籤頁。
示例
js
// This will log the width of the viewport
console.log(window.innerWidth);
// This will log the width of the frame viewport within a frameset
console.log(self.innerWidth);
// This will log the width of the viewport of the closest frameset
console.log(parent.innerWidth);
// This will log the width of the viewport of the outermost frameset
console.log(top.innerWidth);
演示
HTML
html
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
JavaScript
js
const heightOutput = document.querySelector("#height");
const widthOutput = document.querySelector("#width");
function updateSize() {
heightOutput.textContent = window.innerHeight;
widthOutput.textContent = window.innerWidth;
}
updateSize();
window.addEventListener("resize", updateSize);
結果
您也可以 在單獨的頁面上檢視演示程式碼的結果。
規範
| 規範 |
|---|
| CSSOM 檢視模組 # dom-window-innerwidth |
瀏覽器相容性
載入中…