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

瀏覽器相容性

另見