Screen对象提供设备物理屏幕参数而非浏览器窗口尺寸,包括只读属性screen.width/height(总像素尺寸)、availWidth/availHeight(扣除系统UI的可用区域)、colorDepth/pixelDepth(色深)、orientation(屏幕方向),不随缩放或窗口调整变化,且仅反映主屏信息。

JavaScript 的 Screen 对象用于获取用户设备的屏幕信息,它提供的是**物理或系统级显示参数**,不是当前浏览器窗口尺寸。注意:这些值通常不可写,且部分属性在不同浏览器或缩放/多屏环境下可能有差异。
常用只读属性说明
screen.width 和 screen.height
返回屏幕的总宽度和高度(单位:像素),以设备像素为单位。例如:1920 × 1080 表示全高清屏幕。
screen.availWidth 和 screen.availHeight
返回屏幕**可用区域**的宽高,已扣除任务栏、Dock、菜单栏等系统 UI 占用空间。一般比 width/height 略小。
screen.colorDepth 和 screen.pixelDepth
返回屏幕色深(如 24)和像素深度(通常与 colorDepth 相同),表示每个像素能显示的颜色位数。
screen.orientation(需注意兼容性)
返回 ScreenOrientation 对象,包含当前屏幕方向(portrait-primary、landscape-secondary 等)。需配合 orientationchange 事件监听旋转变化。
基础用法示例
直接访问即可:
console.log('屏幕总宽高:', screen.width, '×', screen.height);
console.log('可用宽高:', screen.availWidth, '×', screen.availHeight);
console.log('色深:', screen.colorDepth);
console.log('方向:', screen.orientation?.type);
注意事项与常见误区
-
不是视口尺寸:要获取网页可视区域大小,请用
document.documentElement.clientWidth或window.innerWidth,而非screen。 -
不响应式更新:screen 属性是静态的,不会随浏览器缩放、窗口调整而改变;但屏幕旋转可能触发
screen.orientation变化。 - 多显示器场景:screen 对象始终返回主屏幕参数,无法直接获取副屏信息(浏览器暂不支持)。
-
隐私限制趋势:部分浏览器(如 Safari)可能对
screen某些属性返回模糊值(如四舍五入到最近的百位),以降低指纹识别风险。
简单判断横竖屏的方法
可结合 screen.width 和 screen.height 做粗略判断(适合桌面端):
const isLandscape = screen.width > screen.height; console.log(isLandscape ? '横屏' : '竖屏');
更准确的方式是监听 screen.orientation 或使用 CSS 媒体查询 @media (orientation: landscape)。
立即学习“Java免费学习笔记(深入)”;


















