Window: innerWidth 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

只读的 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

浏览器兼容性

另见