当使用< svg> 标签直接将SVG包含在文档中时,可以通过文档的样式表将CSS样式应用于SVG。但是,我试图应用一个样式到嵌入的SVG(使用< object> 标签)。
When an SVG is directly included in a document using the <svg> tag, you can apply CSS styles to the SVG via the document's stylesheet. However, I am trying to apply a style to an SVG which is embedded (using the <object> tag).
是否可以使用下列程式码?
Is it possible to use anything such as the following code?
object svg { fill: #fff; }推荐答案
样式不适用于文档边界。
Short answer: no, since styles don't apply across document boundaries.
但是,由于您有一个< object> 使用脚本将样式表插入svg文档。
However, since you have an <object> tag you can insert the stylesheet into the svg document using script.
这样的代码假设< object> 已完全载入:
Something like this, and note that this code assumes that the <object> has loaded fully:
var svgDoc = yourObjectElement.contentDocument; var styleElement = svgDoc.createElementNS("www.w3/2000/svg", "style"); styleElement.textContent = "svg { fill: #fff }"; // add whatever you need here svgDoc.getElementById("where-to-insert").appendChild(styleElement);也可以插入< link> 元素引用外部样式表:
It's also possible to insert a <link> element to reference an external stylesheet:
var svgDoc = yourObjectElement.contentDocument; var linkElm = svgDoc.createElementNS("www.w3/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);另一种选择是使用第一种方法插入一个样式元素,导入规则,例如 styleElement.textContent =@import url(my-style.css)。
Yet another option is to use the first method, to insert a style element, and then add an @import rule, e.g styleElement.textContent = "@import url(my-style.css)".
当然你也可以从svg文件直接链接到样式表,而不需要做任何脚本。以下任一项都应该有效:
Of course you can directly link to the stylesheet from the svg file too, without doing any scripting. Either of the following should work:
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="my-style.css" type="text/css"?> <svg xmlns="www.w3/2000/svg"> ... rest of document here ... </svg>或:
<svg xmlns="www.w3/2000/svg"> <defs> <link href="my-style.css" type="text/css" rel="stylesheet" xmlns="www.w3/1999/xhtml"/> </defs> ... rest of document here ... </svg>2015年更新:您可以使用 jquery-svg plugin for apply js scripts and css styles to an embedded SVG。
Update 2015: you can use jquery-svg plugin for apply js scripts and css styles to an embedded SVG.
更多推荐
如何将样式应用到嵌入式SVG?
发布评论