JS Screen对象:获取屏幕信息

12个月前 (04-27)
JavaScript screen 对象中包含了有关计算机屏幕的信息,例如分辨率、宽度、高度等,我们可以通过 window 对象的 screen 属性来获取它。由于 window 对象是一个全局对象,因此在使用 window.screen 时可以省略 window 前缀,例如 window.screen.width 可以简写为 screen.width

screen 对象中的属性

下表中列举了 JavaScript screen 对象中常用的属性及其描述:

属性

说明

availTop

返回屏幕上方边界的个像素点(大多数情况下返回 0)

availLeft

返回屏幕左边边界的个像素点(大多数情况下返回 0)

availHeight

返回屏幕的高度(不包括 Windows 任务栏)

availWidth

返回屏幕的宽度(不包括 Windows 任务栏)

colorDepth

返回屏幕的颜色深度(color depth),根据 CSSOM(CSS 对象模型)视图,为兼容起见,该值总为 24。

height

返回屏幕的完整高度

pixelDepth

返回屏幕的位深度/色彩深度(bit depth),根据 CSSOM(CSS 对象模型)视图,为兼容起见,该值总为 24

width

返回屏幕的完整宽度

orientation

返回当前屏幕的方向


示例代码如下:

document.write(screen.availTop + "<br>"); // 输出:0

document.write(screen.availLeft + "<br>"); // 输出:0

document.write(screen.availHeight + "<br>");// 输出:1050

document.write(screen.availWidth + "<br>"); // 输出:1920

document.write(screen.height + "<br>"); // 输出:1080

document.write(screen.width + "<br>"); // 输出:1920

document.write(screen.colorDepth + "<br>"); // 输出:24

document.write(screen.pixelDepth + "<br>"); // 输出:24

console.log(screen.orientation); // 输出:ScreenOrientation {angle: 0, type: "landscape-primary", onchange: null}

获取屏幕的宽度和高度

您可以使用 screen 对象的 width 和 height 属性来获取用户计算机屏幕的宽度和高度(单位为像素),示例代码如下:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>JavaScript</title>

</head>

<body>

<button type="button" onclick="getResolution();">获取屏幕的宽度和高度</button>

<script type="text/javascript">

function getResolution() {

alert("您计算机屏幕的尺寸为:" + screen.width + "x" + screen.height);

}

</script>

</body>

</html>

运行结果如下图所示:

JS screen 对象获取屏幕的宽度和高度

图1:获取屏幕的宽度和高度

获取屏幕的颜色深度

您可以使用 screen 对象的 colorDepth 属性来获取用户计算机屏幕的颜色深度,示例代码如下:

提示:颜色深度表示屏幕能够产生多少中颜色,例如,颜色深度为 8 的屏幕可以产生 256 种颜色(即 28),目前大部分屏幕的颜色深度为 24 或 32,一些较旧的显示器的颜色深度为 8 或 16。

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>JavaScript</title>

</head>

<body>

<button type="button" onclick="getColorDepth();">获取颜色深度</button>

<script type="text/javascript">

function getColorDepth() {

alert("您计算机屏幕的颜色深度为:" + screen.colorDepth);

}

</script>

</body>

</html>

运行结果如下图所示:

JS screen 对象获取屏幕的颜色深度

图2:获取屏幕的颜色深度