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

浏览器兼容性

另见