📜  HTML DOM 屏幕对象(1)

📅  最后修改于: 2023-12-03 14:41:46.125000             🧑  作者: Mango

HTML DOM 屏幕对象

HTML DOM 屏幕对象是指浏览器中的 window.screen 对象,它提供了一些有关屏幕的信息,例如屏幕的宽度、高度、像素比等等。

属性
width

获取屏幕宽度,单位为像素(px)。

const screenWidth = window.screen.width;
height

获取屏幕高度,单位为像素(px)。

const screenHeight = window.screen.height;
availWidth

获取可用屏幕宽度,即排除任务栏等非工作区域后的宽度,单位为像素(px)。

const availScreenWidth = window.screen.availWidth;
availHeight

获取可用屏幕高度,即排除任务栏等非工作区域后的高度,单位为像素(px)。

const availScreenHeight = window.screen.availHeight;
colorDepth

获取屏幕颜色深度,单位为比特数(bit)。

const screenColorDepth = window.screen.colorDepth;
pixelDepth

获取屏幕像素深度,也是颜色深度,单位为比特数(bit)。

const screenPixelDepth = window.screen.pixelDepth;
orientation

获取屏幕方向,不同的终端可能有不同的值,例如 0 表示纵向(portrait),90 表示横向(landscape-right),-90 表示横向(landscape-left)。

const screenOrientation = window.screen.orientation;
方法
setTimeout()

在给定的时间后执行一个函数或一段代码。

// 在 3 秒后弹出一个提示框
window.screen.setTimeout(() => {
  alert('3 秒过去了!');
}, 3000);
setInterval()

每隔一定时间执行一次一个函数或一段代码。

// 每隔 2 秒弹出一个提示框
const timer = window.screen.setInterval(() => {
  alert('2 秒过去了!');
}, 2000);

// 停止定时器,不再弹出提示框
window.screen.clearInterval(timer);
matchMedia()

返回一个 MediaQueryList 对象,用于检测文档是否满足指定的 CSS 媒体查询条件。

// 创建一个符合媒体查询条件的 MediaQueryList 对象
const mediaQuery = window.screen.matchMedia('(min-width: 768px)');

// 检测 document 是否符合媒体查询条件
if (mediaQuery.matches) {
  // 在宽度大于等于 768px 的屏幕上运行的代码
} else {
  // 在宽度小于 768px 的屏幕上运行的代码
}
总结

HTML DOM 屏幕对象提供了一些有用的属性和方法,可以帮助开发者获取和操作屏幕相关的信息。通过合理使用这些属性和方法,可以使网站或应用程序更加适配不同屏幕大小和方向的终端设备。