如何在 JavaScript 中获取浏览器窗口的内部高度和内部宽度?
在本文中,我们将学习如何使用 JavaScript 获取浏览器窗口的内部高度和内部宽度。
JavaScript 定义了 window 对象的方法和属性。这些属性包括内部高度和内部宽度,可以帮助我们计算窗口内容区域的高度和宽度。
有两种方法可以计算窗口的内部高度和内部宽度。
使用 innerHeight 和 innerWidth 属性 - 为了获取内部高度和内部宽度,JavaScript 提供了一些属性,例如 window.innerHeight和 window.innerWidth。使用这些属性,可以轻松找到浏览器窗口的高度和宽度。让我们分别讨论它们。
使用 clientHeight 和 clientWidth 属性 - 同样,Element.clientHeight 和 Element.clientWidth 属性分别返回当前元素的内部高度和宽度(以像素为单位)。如果元素没有任何 CSS,则这些属性的值为0。
语法
内部高度属性用于计算窗口内容区域的高度。内部高度属性的语法如下:
window.innerHeight or document.documentElement.clientHeight
内部宽度属性用于计算窗口内容区域的高度。内部宽度属性的语法如下:
Window.innerWidth or document.documentElement.clientWidth
示例 1
以下示例使用 window 对象的innerHeight 和innerWidth 属性返回窗口的高度和宽度。
<html>
<head>
<title>To calculate Inner Height and Inner Width of a window</title>
</head>
<body>
<p id="text1"></p>
<button onclick="calculateHeight()">Click Here</button>
<p id="text2"></p>
<script>
text1.innerHTML = "Click the below button to calculate Height of a window";
function calculateHeightAndWidth(){
var height = window.innerHeight;
var width = window.innerWidth;
text2.innerHTML = " Height : "+height+" pixels"+" Width: "+width+" pixels";
}
</script>
</body>
</html>
执行以上代码后,将生成以下输出。
示例 2
以下示例使用 window 对象的clientHeight 和clientWidth 属性返回窗口的高度和宽度。
<html>
<head>
<title>To calculate Inner Height and Inner Width of a window</title>
</head>
<body>
<p id="text1"></p>
<button onclick="calculateHeight()">Click Here</button>
<p id="text2"></p>
<script>
text1.innerHTML = "Click the below button to calculate Height of a window";
function calculateHeightAndWidth(){
var height = document.documentElement.clientHeight;
var width = document.documentElement.clientWidth;
text2.innerHTML = " Height : "+height+" pixels"+" Width: "+width+" pixels";
}
</script>
</body>
</html>
执行以上代码后,将生成以下输出。
示例 3
以下示例使用document.body.clientHeight/Width计算窗口的高度和宽度。以上示例和以下示例的区别在于,document.documentElement 获取 html 元素,而document.body 获取 body 元素。
<html>
<head>
<title>To calculate Inner Height and Inner Width of a window</title>
</head>
<body>
<p id="text1"></p>
<button onclick="calculateHeight()">Click Here</button>
<p id="text2"></p>
<script>
text1.innerHTML = "Click the below button to calculate Height of a window";
function calculateHeightAndWidth(){
var height = document.body.clientHeight;
var width = document.body.clientWidth;
text2.innerHTML = " Height : "+height+" pixels"+" Width: "+width+" pixels";
}
</script>
</body>
</html>
执行以上代码后,将生成以下输出。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP