当使用 <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.
但是,由于您有一个 标签,您可以使用脚本将样式表插入到 svg 文档中.
However, since you have an <object> tag you can insert the stylesheet into the svg document using script.
类似这样的事情,请注意,此代码假定 已完全加载:
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);也可以插入 元素来引用外部样式表:
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);另一种选择是使用第一种方法,插入一个样式元素,然后添加一个@import 规则,例如 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 插件来应用 js 脚本和 css 样式到嵌入式 SVG.
Update 2015: you can use jquery-svg plugin for apply js scripts and css styles to an embedded SVG.
更多推荐
如何将样式应用于嵌入式 SVG?
发布评论