SVGStyleElement: sheet 属性

Baseline 已广泛支持

此功能已成熟,并可在许多设备和浏览器版本上运行。自 2023 年 3 月以来,它已在各种浏览器中可用。

SVGStyleElement.sheet 只读属性返回与给定 SVG 样式元素相对应的 CSSStyleSheet,如果没有则返回 null

一个 CSSStyleSheet 对象,如果元素没有关联的样式表,则返回 null

示例

此示例演示了如何获取与元素关联的 CSS 样式表。

HTML

HTML 包含一个 <circle> 的 SVG 定义。

html
<textarea id="log" rows="3" cols="50"></textarea>
<svg
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink">
  <circle cx="50" cy="50" r="25" />
</svg>

JavaScript

下面的代码创建了一个 style 元素(一个 SVGStyleElement)并将其添加到 SVG 中。

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.sheet 记录与此新元素关联的样式表和 CSS 规则。为了使

js
// Log the sheet associated with this new element.
const log = document.getElementById("log");
log.value = `${style.sheet} with rules[0].cssText:\n ${style.sheet.rules[0].cssText}`;

结果

结果如下所示。成功时,日志显示应用于 SVG 圆的 CSSStyleSheet 对象。

规范

规范
CSS 对象模型 (CSSOM)
# dom-linkstyle-sheet

浏览器兼容性

另见