如何使用 JavaScript 计算窗口的宽度和高度?

在这篇文章中,我们将探讨如何使用 JavaScript 来计算窗口的宽度与高度。假设我们有一个正在窗口中运行的 HTML 文档,我们需要找到该窗口的高度和宽度。我们可以利用 Window innerWidth 属性来返回窗口内容区域的宽度,并使用 Window innerHeight 属性来返回窗口内容区域的高度。这两个属性都是只读属性。

语法:

window.innerWidth
window.innerHeight

返回值: 它返回一个数字,表示窗口内容区域的宽度和内部高度(以像素为单位)。

示例 1:

这个例子使用 window.innerHeightwindow.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.clientHeightdocument.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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/48783.html
点赞
0.00 平均评分 (0% 分数) - 0