在这篇文章中,我们将探讨如何使用 JavaScript 来计算窗口的宽度与高度。假设我们有一个正在窗口中运行的 HTML 文档,我们需要找到该窗口的高度和宽度。我们可以利用 Window innerWidth 属性来返回窗口内容区域的宽度,并使用 Window innerHeight 属性来返回窗口内容区域的高度。这两个属性都是只读属性。
语法:
window.innerWidth
window.innerHeight
返回值: 它返回一个数字,表示窗口内容区域的宽度和内部高度(以像素为单位)。
示例 1:
这个例子使用 window.innerHeight 和 window.innerWidth 属性来获取窗口的高度和宽度。innerHeight 属性用于返回窗口的高度,而 innerWidth 属性用于返回窗口的宽度。
HTML
Calculate Width and Height of the Window
GeeksforGeeks
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to get the"
+ " width and height of the Window";
function GFG_Fun() {
var width = window.innerWidth;
var Height = window.innerHeight;
el_down.innerHTML = "Width: " + width + " pixels"
+ ", " + "Height: " + Height + " pixels";
}
输出:
!imagewindow.inner Property
示例 2:
这个例子使用 document.documentElement.clientHeight 和 document.documentElement.clientWidth 方法来分别获取窗口的高度和宽度。
HTML
Calculate Width and Height of the Window
GeeksforGeeks
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to get the"
+ " width and height of the window";
function GFG_Fun() {
el_down.innerHTML = "Width:"
+ document.documentElement.clientWidth
+ " pixels"
+ ", "
+ "Height:"
+ document.documentElement.clientHeight
+ " pixels";
}
输出:
!imagedocumentElement.client Method