如何将样式应用于嵌入式 SVG?

编程入门 行业动态 更新时间:2024-10-10 10:23:32
本文介绍了如何将样式应用于嵌入式 SVG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当使用 <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?

本文发布于:2023-11-28 19:57:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643759.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   如何将   嵌入式   样式   SVG

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!