以程式設計方式測試媒體查詢

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

瀏覽器相容性

另見