视口是指浏览器中实际用于显示网页的部分,要测量视口的宽度和高度,请检查 document.documentElement 对象中的 clientWidthclientHeight 属性。

const viewportWidth = document.documentElement.clientWidth
const viewportHeight = document.documentElement.clientHeight

注意:视口值不包括水平或垂直滚动条。

如果要计算包含滚动条的大小,请使用 window.innerWidthwindow.innerHeight 属性。

window.innerWidth
window.innerHeight

如果您想获得整个浏览器窗口的大小,请使用 window.outerWidthwindow.outerHeight 属性。它们返回浏览器窗口的完整大小,包括标题栏。

window.outerWidth
window.outerHeight

设备大小

window.screen.widthwindow.screen.height 属性返回屏幕的完整分辨率(包含底部的任务栏):

const fullWidth = window.screen.width
const fullHeight = window.screen.height
image.png

window.screen.availWidthwindow.screen.availHeight(不包含任务栏)

const availableWidth = window.screen.availWidth
const availableHeight = window.screen.availHeight
image.png

文档大小

文档大小

使用 document.body 上的 clientWidthclientHeight 属性来获取 document 的大小。

const docWidth = document.body.clientWidth
const docHeight = document.body.clientHeight