MediaQueryList: matches 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

MediaQueryList 介面的 **matches** 只讀屬性是一個布林值,如果 document 當前匹配媒體查詢列表,則返回 true,否則返回 false

透過偵聽在 MediaQueryList 上觸發的 change 事件,可以得知 matches 值的變化。

如果 document 當前匹配媒體查詢列表,則返回 true;否則返回 false

示例

此示例透過使用 orientation 媒體特性建立媒體查詢來檢測視口方向變化。

js
const mql = window.matchMedia("(orientation:landscape)");
mql.addEventListener("change", (event) => {
  if (event.matches) {
    console.log("Now in landscape orientation");
  } else {
    console.log("Now in portrait orientation");
  }
});

規範

規範
CSSOM 檢視模組
# dom-mediaquerylist-matches

瀏覽器相容性

另見