You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript获取显示器硬件尺寸?

获取显示器硬件尺寸的JavaScript方案

首先得澄清一个误区:你提到的 screen.width、screen.height 其实不会随浏览器窗口大小变化——它们返回的是显示器的原生物理分辨率,是硬件固定的参数。你之前觉得这些值跟着窗口变,大概率是把它们和 window.innerWidth/window.innerHeight(浏览器可视区域的大小)搞混了。

1. 获取显示器原生分辨率(固定硬件参数)

以下几个属性都是和显示器硬件绑定的固定值,不受窗口大小影响:

  • screen.width:显示器原生宽度(物理像素)
  • screen.height:显示器原生高度(物理像素)
  • screen.devicePixelRatio:设备像素比(物理像素与CSS像素的比例,比如Windows开125%缩放时这个值是1.25)

如果要估算显示器的物理英寸尺寸,可以用分辨率结合像素密度计算:

// 估算物理宽度(英寸)
const physicalWidth = screen.width / screen.devicePixelRatio / 96;
// 估算物理高度(英寸)
const physicalHeight = screen.height / screen.devicePixelRatio / 96;

说明:96是标准CSS像素密度,实际设备可能有细微差异,结果是近似值

2. 多显示器场景的处理

如果用户用的是多显示器,screen 对象返回的是当前浏览器所在显示器的参数。要获取所有显示器的信息,可以用浏览器的 Display API(需要HTTPS环境,部分浏览器支持):

if ('getDisplays' in window) {
  window.getDisplays().then(displays => {
    displays.forEach(display => {
      console.log(`显示器名称: ${display.name}`);
      console.log(`原生分辨率: ${display.width}x${display.height}`);
      console.log(`估算物理尺寸: ${(display.width / display.devicePixelRatio / 96).toFixed(1)} x ${(display.height / display.devicePixelRatio / 96).toFixed(1)} 英寸`);
    });
  });
}

3. 更靠谱的设备类型判断方案

如果你的核心需求是区分桌面/平板/移动设备,而非精确获取显示器物理尺寸,其实没必要硬抓硬件参数——以下两种方案更实用:

  • 用 navigator.userAgentData(现代浏览器支持):
const isMobile = navigator.userAgentData?.mobile;
const platform = navigator.userAgentData?.platform; // 返回"Windows"、"macOS"、"Android"、"iOS"等
  • 结合媒体查询(适配响应式逻辑):
const isMobile = window.matchMedia('(max-width: 767px)').matches;
const isTablet = window.matchMedia('(min-width: 768px) and (max-width: 1023px)').matches;
const isDesktop = window.matchMedia('(min-width: 1024px)').matches;

这种方式更贴合前端开发的实际场景,比依赖硬件尺寸灵活得多。

内容的提问来源于stack exchange,提问作者Blake McBride

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:05:26