值
一个 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 |
浏览器兼容性
加载中…