SVGStyleElement: media 屬性

Baseline 已廣泛支援

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

SVGStyleElement.media 屬性是一個媒體查詢字串,對應於給定 SVG style 元素的 media 屬性。

查詢必須匹配才能應用樣式。

一個定義有效媒體查詢列表的字串,其中包含一個或多個逗號分隔的值。例如 "screen, print",或 "all"(預設值)。

該值使用對應 style 的 media 屬性中指定的字串進行初始化。

示例

此示例演示瞭如何以程式設計方式獲取和設定在 SVG 定義中定義的 style 上的 media 屬性。

HTML

HTML 包含一個 <circle> 的 SVG 定義,其中包含一個 <style> 元素,該元素是基於媒體查詢 "(width >= 600px)" 的條件渲染的。我們還定義了一個 button,用於顯示當前樣式並更改樣式。

html
<button></button>
<svg
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink">
  <circle cx="60" cy="60" r="50" />
</svg>

JavaScript

下面的程式碼透過 id 獲取 style 元素(一個 SVGStyleElement)。

js
const svg = document.querySelector("svg");
// Create the `style` element in the SVG namespace
const style = document.createElementNS("http://www.w3.org/2000/svg", "style");
const node = document.createTextNode("circle { fill: red; }");
svg.appendChild(style);
style.appendChild(node);

然後,我們新增一個函式來設定按鈕文字,以顯示 style 的 media 屬性的當前值以及當前視窗的寬度。呼叫此函式來設定初始按鈕文字,並在視窗大小調整或按下按鈕時呼叫。按鈕的事件處理程式還會設定 style 的 media 屬性的值。

js
const button = document.querySelector("button");

function setButtonText() {
  button.textContent = `Media: ${style.media} (Width: ${window.innerWidth})`;
}
setButtonText();

addEventListener("resize", () => {
  setButtonText();
});

button.addEventListener("click", () => {
  style.media = "(width >= 700px)";
  setButtonText();
});

結果

結果如下所示。按鈕文字顯示最初應用於 SVG 樣式的 media 屬性的值,以及當前幀的寬度(因為程式碼在幀內執行)。將幀的寬度縮小到按鈕中顯示的媒體查詢寬度,以檢視樣式被應用。按下按鈕可切換 style 上 media 屬性的值(這將反映在按鈕上)。

注意: media 屬性可以設定為任何字串,但如果字串不是有效的媒體查詢,則會被忽略。

規範

規範
Scalable Vector Graphics (SVG) 2
# __svg__SVGStyleElement__media

瀏覽器相容性

另見