获取屏幕分辨率应使用window.screen.width和window.screen.height,它们返回显示器的物理像素尺寸;而浏览器视口尺寸则通过window.innerwidth/window.innerheight或document.documentelement.clientwidth/clientheight获取,表示当前窗口内可显示内容的区域大小;二者区别在于屏幕分辨率是固定硬件属性,视口尺寸随浏览器窗口调整变化;设备像素比(dpr)影响css像素与物理像素的映射关系,高dpr设备上一个css像素对应多个物理像素,需在图片加载和canvas绘制时进行适配;浏览器缩放会改变视口尺寸但不影响屏幕分辨率,多显示器环境下screen对象通常仅反映主屏信息,全屏模式下视口尺寸会与屏幕分辨率一致,旧版ie需用document对象属性替代innerwidth/height以确保兼容性。
在JavaScript里,获取屏幕分辨率主要通过
window.screen
如果你想知道用户整个屏幕的宽度和高度,最直接的方式就是使用
window.screen.width
window.screen.height
举个例子,如果你的显示器是1920x1080的,那么
screen.width
screen.height
// 获取屏幕分辨率 const screenWidth = window.screen.width; const screenHeight = window.screen.height; console.log(`屏幕分辨率: ${screenWidth}x${screenHeight}`); // 获取浏览器视口尺寸(不含滚动条、工具栏等) const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; console.log(`浏览器视口: ${viewportWidth}x${viewportHeight}`); // 获取文档元素(HTML)的尺寸,通常等同于视口,但更稳定 const documentWidth = document.documentElement.clientWidth; const documentHeight = document.documentElement.clientHeight; console.log(`文档区域: ${documentWidth}x${documentHeight}`);
这是一个非常常见的误解,我发现很多开发者在刚接触前端布局时都会把它们混淆。简单来说,屏幕分辨率是你的显示器能显示的最大像素点数量,它是个固定值,除非你换显示器或者改变操作系统的显示设置。而浏览器视口尺寸,也就是
window.innerWidth
window.innerHeight
想象一下,你有一张很大的画布(屏幕),而你的浏览器只是这张画布上的一扇窗户。
screen.width/height
window.innerWidth/innerHeight
此外,还有一个
document.documentElement.clientWidth
document.documentElement.clientHeight
window.innerWidth/innerHeight
document.documentElement
这块内容就有点意思了,尤其是对于高DPI(Retina)屏幕来说,它会引入一个“设备像素”和“CSS像素”的概念。
window.devicePixelRatio
devicePixelRatio
那么,这和分辨率有什么关系呢?
window.screen.width
window.screen.height
width: 100px;
window.innerWidth
理解DPR非常重要,因为它影响了图片资源的加载策略(比如
srcset
虽然
window.screen
window.innerWidth
首先是浏览器缩放。用户在浏览器里按
Ctrl/Cmd +
-
window.innerWidth
window.innerHeight
window.screen.width
window.screen.height
innerWidth
其次是多显示器设置。当用户连接了多个显示器时,
window.screen.width
window.screen.height
再有就是全屏模式。当浏览器进入全屏模式时(比如播放视频),
window.innerWidth
window.innerHeight
window.screen.width
window.screen.height
最后,早期的IE浏览器(比如IE8及更早版本)可能对
window.innerWidth
window.innerHeight
document.documentElement.clientWidth
document.documentElement.clientHeight
以上就是js怎么获取屏幕分辨率的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号