MediaQueryList.matches

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

MediaQueryList 接口的 matches 只读属性是一个布尔值,如果 document 当前匹配媒体查询列表,该属性返回 true,否则返回 false

通过侦听发生在 MediaQueryListchange 事件,当 matches 的值发生变化时,你可以收到通知。

一个布尔值,如果 document 目前匹配媒体查询列表,该值为 true,反之为 false

示例

该示例通过使用 orientation 媒体查询特性来创建一个媒体查询,以检测视口横纵方向的变化:

js
function addMQListener(mq, callback) {
  if (mq.addEventListener) {
    mq.addEventListener("change", callback);
  } else {
    mq.addListener(callback);
  }
}

addMQListener(window.matchMedia("(orientation:landscape)"), (event) => {
  if (event.matches) {
    /* 现在是横向 */
  } else {
    /* 现在是纵向 */
  }
});

规范

Specification
CSSOM View Module
# dom-mediaquerylist-matches

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
matches

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见