在 JavaScript 中获取视口尺寸
浏览器视口
是可以查看网页内容的窗口区域。本文将学习如何在 JavaScript 中获取 Viewport Dimension。
Javascript 提供了两种方法来找出设备的视口。
- 使用
window.innerWidth
和window.innerHeight
- 使用
document.documentElement.clientWidth
和.clientHeight
在 JavaScript 中使用 window.innerWidth
获取视口宽度
窗口的只读 innerWidth
属性返回窗口的内部宽度(以像素为单位)。这包括垂直滚动条的宽度
。
窗口的内部高度可以从 innerHeight
属性获得。
语法:
let intViewportWidth = window.innerWidth;
一个整数值表示窗口布局 viewport
的宽度(以像素为单位)。此属性没有默认值并且是只读的。
要更改窗口的宽度,请使用窗口的方法之一来更改窗口的大小,例如 resizeBy()
或 resizeTo()
。
有关 window.innerWidth 的更多信息。
function resizeEventListener() {
console.log('innerHeight', window.innerHeight);
console.log('innerWidth', window.innerWidth);
}
window.addEventListener('resize', resizeEventListener);
我们在调整浏览器窗口大小之前和之后计算窗口的内部高度和宽度。
要获得减去滚动条和边框的窗口宽度,请改用 clientWidth
属性。结果可能因窗口而异。
输出:
// Before resize
"innerHeight", 219
"innerWidth", 1326
// After resize
"innerHeight", 166
"innerWidth", 974
在 JavaScript 中使用 document.documentElement.clientWidth
获取视口宽度
对于内联项目和没有 CSS 的元素,属性 element.Clientwidth
为零;否则,它是以像素为单位的元素的内部宽度。
包括内边距,但不包括边框、边距和垂直滚动条。
当在根元素上使用 clientWidth
或文档处于 quirks mode
时,将返回视口的宽度,不包括滚动条。
语法:
var intElemClientWidth = element.clientWidth;
intElemClientWidth
是一个整数值,表示元素的 clientWidth
(以像素为单位)。clientWidth
属性是只读的。
更多信息请见 element.clientWidth。
function resizeEventListener() {
console.log('clientWidth', document.documentElement.clientWidth);
console.log('clientHeight', document.documentElement.clientHeight);
}
window.addEventListener('resize', resizeEventListener);
我们计算客户的内部高度和宽度。
输出:
// Before resize
"clientWidth", 1326
"clientHeight", 219
// After resize
"clientWidth", 974
"clientHeight", 166
要查看结果,请单击此处。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。