以编程方式测试媒体查询

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

DOM 提供了通过 MediaQueryList 接口及其方法和属性,以编程方式测试 媒体查询 结果的功能。创建 MediaQueryList 对象后,你可以检查 查询 的结果,或者在结果改变时接收通知。

创建媒体查询列表

在评估媒体查询结果之前,你需要创建表示该查询的 MediaQueryList 对象。为此,请使用 window.matchMedia 方法。

例如,设置一个查询列表以确定设备是横向还是纵向 方向

js
const mediaQueryList = window.matchMedia("(orientation: portrait)");

检查查询结果

创建媒体查询列表后,可以通过查看其 matches 属性的值来检查查询结果。

js
if (mediaQueryList.matches) {
  /* The viewport is currently in portrait orientation */
} else {
  /* The viewport is not currently in portrait orientation, therefore landscape */
}

接收查询通知

如果你需要持续了解查询评估结果的变化,注册一个 监听器 比轮询查询结果更高效。为此,在 MediaQueryList 对象上调用 addEventListener() 方法,并传入一个在媒体查询状态改变时(例如,媒体查询测试从 true 变为 false)调用的回调函数。

js
// Create the query list.
const mediaQueryList = window.matchMedia("(orientation: portrait)");

// Define a callback function for the event listener.
function handleOrientationChange(mql) {
  // …
}

// Run the orientation change handler once.
handleOrientationChange(mediaQueryList);

// Add the callback function as a listener to the query list.
mediaQueryList.addEventListener("change", handleOrientationChange);

此代码创建了方向测试媒体查询列表,并为其添加了一个事件监听器。定义监听器后,我们还直接调用了监听器。这使得我们的监听器能够根据当前设备方向进行调整;否则,我们的代码在启动时可能会假定设备处于纵向模式,即使它实际上处于横向模式。

handleOrientationChange() 函数会查看查询结果并处理在方向改变时我们需要做的任何事情。

js
function handleOrientationChange(evt) {
  if (evt.matches) {
    /* The viewport is currently in portrait orientation */
  } else {
    /* The viewport is currently in landscape orientation */
  }
}

上面,我们将参数定义为 evt — 一个 MediaQueryListEvent 类型的事件对象,它还包含 mediamatches 属性,因此你可以通过直接访问 MediaQueryList 或访问事件对象来查询这些特性。

结束查询通知

要停止接收关于媒体查询值变化的通知,请在 MediaQueryList 上调用 removeEventListener(),并传入先前定义的回调函数的名称。

js
mediaQueryList.removeEventListener("change", handleOrientationChange);

规范

规范
CSSOM 视图模块
# the-mediaquerylist-interface

浏览器兼容性

另见