首页 > 解决方案 > 如何从外部 SVG 文件中提取 SVG 元素并附加到 HTML?

问题描述

这个问题类似,但答案没有帮助。

目标是加载外部 SVG 文件(例如https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/android.svg),提取 SVG 元素,并将其附加到 HTML作为内联 SVG 元素。

你怎么能做到这一点?

我们只想使用 jQuery,没有其他第三方库。

标签: javascripthtmlsvg

解决方案


如果你有这样的 svg 元素

<svg id="mySvgElement" width="100" height="100"></svg>

然后,您可以获得一个外部 svg 文件并将其内容放入您的 svg 元素中,如下所示:

$.get(externalSvgUrl, function(response){
    var content = $(response).html();
    $("#mySvgElement").html(content);
});

推荐阅读