JavaScript screen 获取屏幕尺寸并与视口比较

浏览器报告的屏幕尺寸可用 window.screen.width 和 height 获取。window.innerWidth 和 innerHeight 表示布局视口,也就是用于排布页面的区域。响应式布局应以视口为依据。

读取 Screen 提供的尺寸

Screen 的属性是只读的。尺寸以 CSS 像素表示,不代表屏幕的物理分辨率。隐私设置和多显示器配置可能影响浏览器报告的值。CSSOM View · Screen

属性 测量内容
width, height 浏览器报告的完整屏幕尺寸
availWidth, availHeight 报告为窗口可用的屏幕区域
colorDepth, pixelDepth 报告的每像素颜色位数

availWidth 和 availHeight 可能扣除操作系统保留的区域。与总尺寸的差值不能准确反映任务栏高度。

区分布局视口和可见区域

innerWidth 包含垂直滚动条占用的空间。在标准模式下,可用 document.documentElement.clientWidth 排除这部分空间。可用 CSS 媒体查询调整布局,并用 matchMedia() 在 JavaScript 中检查相同的条件。CSSOM View · Window.innerWidth

console.log(window.screen.width);
console.log(window.innerWidth);
console.log(document.documentElement.clientWidth);
console.log(window.matchMedia('(max-width: 600px)').matches);

双指缩放可能改变视觉视口,也就是用户实际看到的区域。在支持的环境中,可读取 window.visualViewport.width。布局视口不一定按相同比例变化。CSSOM View · VisualViewport

在独立 HTML 页面中比较尺寸

将代码以 UTF-8 保存为 screen-info.html,再用浏览器打开。在同一台显示器上缩窄窗口,比较 innerWidth 和 screen.width。如果浏览器报告的是屏幕尺寸,screen.width 可能保持不变。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较屏幕和视口尺寸</title>
</head>
<body>
<button id="refresh" type="button">重新读取</button>
<pre id="result" aria-live="polite"></pre>
<script>
const result = document.querySelector('#result');
const { screen, visualViewport } = window;
const unavailable = "不可用";

function showSizes() {
  const values = [
    ['screen.width', screen.width],
    ['screen.height', screen.height],
    ['screen.availWidth', screen.availWidth],
    ['screen.availHeight', screen.availHeight],
    ['screen.colorDepth', screen.colorDepth],
    ['screen.pixelDepth', screen.pixelDepth],
    ['window.innerWidth', window.innerWidth],
    ['window.innerHeight', window.innerHeight],
    ['document.documentElement.clientWidth', document.documentElement.clientWidth],
    ['visualViewport.width', visualViewport?.width ?? unavailable],
    ['visualViewport.height', visualViewport?.height ?? unavailable]
  ];
  result.textContent = values.map(([name, value]) => `${name}: ${value}`).join('\n');
}

document.querySelector('#refresh').addEventListener('click', showSizes);
window.addEventListener('resize', showSizes);
visualViewport?.addEventListener('resize', showSizes);
showSizes();
</script>
</body>
</html>

窗口或视觉视口的尺寸改变时,示例会更新读数。如果移到其他显示器时没有自动更新,可以点击按钮重新读取。视觉视口对象不可用时,示例会显示提示。