Javascript 如何在 <img> 元素中访问 SVG 文件的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8102528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:44:33  来源:igfitidea点击:

How do you access the contents of an SVG file in an <img> element?

javascripthtmlsvg

提问by user783146

Say you have this in your HTML:

假设你的 HTML 中有这个:

<img src='example.svg' />

<img src='example.svg' />

How would you access the contents ( ie. <rect>, <circle>, <ellipse>, etc.. ) of the example.svg via JavaScript?

您将如何<rect>, <circle>, <ellipse>通过 JavaScript 访问 example.svg的内容(即,等)?

回答by Erik Dahlstr?m

It's not possible to get the DOM of a referenced svg from the imgelement.

无法从img元素中获取引用的 svg 的 DOM 。

If you use <object>, <embed>or <iframe>however then you can use .contentDocument(preferred) to get the referenced svg, or .getSVGDocumentwhich may be more compatible with old svg plugins.

如果您使用<object>,<embed>或者<iframe>那么您可以使用.contentDocument(首选)来获取引用的 svg,或者.getSVGDocument它可能与旧的 svg 插件更兼容。

Here's an exampleshowing how to get the DOM of a referenced svg.

这是一个示例,展示了如何获取引用的 svg 的 DOM。

回答by nrabinowitz

I'm pretty sure this isn't possible. The external SVG is not part of the DOM in the way an inline SVG is, and I don't believe you can access the SVG DOM tree from the loading document.

我很确定这是不可能的。外部 SVG 不像内联 SVG 那样是 DOM 的一部分,我不相信您可以从加载文档访问 SVG DOM 树。

What you cando is load the SVG as XML, using an AJAX request, and insert it into the DOM as an inline SVG you can then walk and manipulate. This D3 exampledemonstrates the technique. I think the d3.xml()function used here is more or less equivalent to jQuery's $.ajax()with dataType: "xml".

可以做的是使用 AJAX 请求将 SVG 加载为 XML,然后将其作为内联 SVG 插入到 DOM 中,然后您就可以浏览和操作了。此 D3 示例演示了该技术。我认为d3.xml()这里使用的函数或多或少等同于 jQuery 的$.ajax()with dataType: "xml".

回答by Anton Medvedev

If you are using inlining of SVG into CSS url(data:...)or just using url(*.svg)background, you can embed them into DOM with svg-embed.

如果您使用 SVG 内联到 CSSurl(data:...)或仅使用url(*.svg)背景,您可以使用svg-embed将它们嵌入到 DOM 中。

Support Chrome 11+, Safari 5+, FireFox 4+ and IE9+.

支持 Chrome 11+、Safari 5+、FireFox 4+ 和 IE9+。

回答by Syed

No, not possible but you can just Convert <img>to <svg>as mentioned HEREand you can just access the nodes in svg in DOM.

不,不可能,但您可以像这里提到的那样转换<img><svg>,并且您可以访问 DOM 中 svg 中的节点。