天天看点

Window innerWidth 和 innerHeight 属性

Window innerWidth 和 innerHeight 属性

Window 对象

innerHeight 返回窗口的文档显示区的高度,如果有垂直滚动条,也包括滚动条高度。

innerWidth 返回窗口的文档显示区的宽度,如果有水平滚动条,也包括滚动条高度。

innerWidth 和 innerHeight 是只读属性。

注意:使用

outerWidth 和 outerHeight 属性获取浏览器窗口的宽度与高度。

获取文档显示区的宽度与高度:

设置文档显示区的宽度与高度:

表格中的数字表示支持该属性的第一个浏览器版本号。

属性

innerWidth

1.0

9.0

3.0

innerHeight

注意:IE 8 及更早 IE 版本不支持这两个属性,可以使用 clientWidth 和 clientHeight 属性。

获取窗口的高度与宽度:

var w=window.innerWidth;

var h=window.innerHeight;

以下演示了 innerWidth, innerHeight, outerWidth 和 outerHeight 的使用:

var txt = "";

txt += "<p>innerWidth: " + window.innerWidth + "</p>";

txt += "<p>innerHeight: " + window.innerHeight + "</p>";

txt += "<p>outerWidth: " + window.outerWidth + "</p>";

txt += "<p>outerHeight: " + window.outerHeight + "</p>";

实用的 JavaScript 方案(涵盖所有浏览器,包含 IE8 及以下版本的浏览器):

var w=window.innerWidth

|| document.documentElement.clientWidth

|| document.body.clientWidth;

var h=window.innerHeight

|| document.documentElement.clientHeight

|| document.body.clientHeight;

Window innerWidth 和 innerHeight 属性