Skip to content

JavaScript Screen 对象

window.screen 对象提供关于用户屏幕的信息,例如其尺寸(dimensions)和颜色深度(color depth)。

window.screen 对象可以直接通过 screen 访问(因为 window 是浏览器中的全局对象)。

主要属性 (Key Properties):

  • screen.width: 用户屏幕的总宽度,单位为像素(pixels)。
  • screen.height: 用户屏幕的总高度,单位为像素。
  • screen.availWidth: 屏幕可用于应用窗口的宽度,不包括操作系统(OS)任务栏等界面特性。
  • screen.availHeight: 屏幕可用于应用窗口的高度,不包括操作系统界面特性(如固定的任务栏或菜单栏)。
  • screen.colorDepth: 用于显示一种颜色的位数(也称为位深度)。
  • screen.pixelDepth: 屏幕的位深度(bit depth)。对于现代系统,这通常与 colorDepth 相同。

注意:这些属性反映的是屏幕的功能,不一定反映浏览器窗口的大小。要获取浏览器视口(viewport)的大小,请使用 window.innerWidth 和 window.innerHeight。

screen.width 属性返回用户屏幕的总宽度,单位为像素。

// Assuming an HTML element with id="demo"
// const demoElement = document.getElementById("demo");
// if (demoElement) demoElement.textContent = "Screen Width: " + screen.width + "px";
console.log("Screen Width: " + screen.width + "px");

screen.height 属性返回用户屏幕的总高度,单位为像素。

// const demoElement = document.getElementById("demo");
// if (demoElement) demoElement.textContent = "Screen Height: " + screen.height + "px";
console.log("Screen Height: " + screen.height + "px");

Window Screen Available Width (屏幕可用宽度)

Section titled “Window Screen Available Width (屏幕可用宽度)”

screen.availWidth 属性返回屏幕可用于窗口的宽度,单位为像素,不包括操作系统界面特性,例如固定的任务栏或菜单栏。

// const demoElement = document.getElementById("demo");
// if (demoElement) demoElement.textContent = "Available Screen Width: " + screen.availWidth + "px";
console.log("Available Screen Width: " + screen.availWidth + "px");

Window Screen Available Height (屏幕可用高度)

Section titled “Window Screen Available Height (屏幕可用高度)”

screen.availHeight 属性返回屏幕可用于窗口的高度,单位为像素,不包括操作系统界面特性。

// const demoElement = document.getElementById("demo");
// if (demoElement) demoElement.textContent = "Available Screen Height: " + screen.availHeight + "px";
console.log("Available Screen Height: " + screen.availHeight + "px");

Window Screen Color Depth (屏幕颜色深度)

Section titled “Window Screen Color Depth (屏幕颜色深度)”

screen.colorDepth 属性返回用于表示单个像素颜色的位数。

现代显示器的常见值:

  • 24 bits:表示 16,777,216 种不同颜色(“真彩色”)。
  • 30 bits / 32 bits (通常是 24 位颜色加上 8 位 alpha 通道):可以表示超过十亿种颜色(“深色”),尽管显示器的支持程度各不相同。

较旧的系统可能使用过 16 位(65,536 种颜色,“高彩色”)或 8 位(256 种颜色)。

// const demoElement = document.getElementById("demo");
// if (demoElement) demoElement.textContent = "Screen Color Depth: " + screen.colorDepth + "-bit";
console.log("Screen Color Depth: " + screen.colorDepth + "-bit");
CSS 颜色值,如 #RRGGBB 或 rgb(r,g,b),通常定义 24 位颜色空间(每个通道 8 位)中的颜色。

Window Screen Pixel Depth (屏幕像素深度)

Section titled “Window Screen Pixel Depth (屏幕像素深度)”

screen.pixelDepth 属性也返回屏幕的颜色位深度。

// const demoElement = document.getElementById("demo");
// if (demoElement) demoElement.textContent = "Screen Pixel Depth: " + screen.pixelDepth + "-bit";
console.log("Screen Pixel Depth: " + screen.pixelDepth + "-bit");
对于现代计算机,screen.colorDepth 和 screen.pixelDepth 通常返回相同的值。