简短的回答:不,因为样式不适用于跨文档边界。
然而,既然你有一个<object>
标签,您可以使用脚本将样式表插入到 svg 文档中。
像这样的东西,请注意,此代码假设<object>
已完全加载:
var svgDoc = yourObjectElement.contentDocument;
var styleElement = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style");
styleElement.textContent = "svg { fill: #fff }"; // add whatever you need here
svgDoc.getElementById("where-to-insert").appendChild(styleElement);
也可以插入一个<link>
引用外部样式表的元素:
var svgDoc = yourObjectElement.contentDocument;
var linkElm = svgDoc.createElementNS("http://www.w3.org/1999/xhtml", "link");
linkElm.setAttribute("href", "my-style.css");
linkElm.setAttribute("type", "text/css");
linkElm.setAttribute("rel", "stylesheet");
svgDoc.getElementById("where-to-insert").appendChild(linkElm);
另一种选择是使用第一种方法,插入样式元素,然后添加 @import 规则,例如styleElement.textContent = "@import url(my-style.css)"
.
当然,您也可以直接从 svg 文件链接到样式表,而无需执行任何脚本编写。以下任一方法都应该有效:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="my-style.css" type="text/css"?>
<svg xmlns="http://www.w3.org/2000/svg">
... rest of document here ...
</svg>
or:
<svg xmlns="http://www.w3.org/2000/svg">
<defs>
<link href="my-style.css" type="text/css" rel="stylesheet"
xmlns="http://www.w3.org/1999/xhtml"/>
</defs>
... rest of document here ...
</svg>
2015 更新:您可以使用jquery-svg https://github.com/mberneti/jquery-svg/用于将 js 脚本和 css 样式应用于嵌入式 SVG 的插件。