我在 Inkscape 中创建了一个 SVG 文件。我想使用 xmlHttpRequest 导入 svg 文件,然后从 <g>
注入(inject)数据元素插入 HTML。
但是。由于某种原因,xml 响应省略了 g 元素。当我在浏览器的调试控制台中评估 XMLResponse 时,我可以看到这一点。为什么会发生这种情况?我该如何解决它?
SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="7e3" width="7e3" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" viewBox="0 0 7000 7000">
<metadata>
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
<dc:title/>
</cc:Work>
</rdf:RDF>
</metadata>
<g>
<path d="m2757.3 5004.4-680.5-398.2-481.1 1037.3 168.3-770.3-1135.1-137 784.6-77.9-220.5-1122l316.57 722.13 998.9-556.4-588.96 524.23z" fill="#b80000"/>
<path d="m3412.4 2163.2-160.35-542.71-560.16-80.386 466.6-320.21-96.649-557.59 448.72 344.81 500.43-264.22-189.27 533.31 405.93 394.29-565.7-15.206z" fill="#c5e100"/>
<path d="m5368.2 4458.8-2316.6-2010.7 2271.3 3360.5-934.5-1243.8-1614.2 420 2282.8-768.5-2327 530.8 2258.9 1074.5-149.6-2017.6 490.3-524.8-2267.1 1484.9 2756.7-1066.1-2366.8 1127 1764.8 768.5 723-848.5-721.5-2303.9z" transform="matrix(.81493 0 0 .84227 1190.8 811.58)" fill="#1643bf"/>
</g>
</svg>
Javascript
var svg = document.getElementsByTagName("svg")[0];
var g = svg.getElementsByTagName("g")[0];
xmlHTTP = new XMLHttpRequest();
xmlHTTP.onload = function() {
if (this.readyState == 4 && this.status == 200) {
draw();
};
xmlHTTP.open("GET", "drawing.svg", true);
xmlHTTP.send();
function draw(){
var svgFile, extG;
svgFile = xmlHTTP.responseXML;// <---evaluates without the g element from the svg file
extG = svgFile.getElementsByTagName("g");
svg.replaceChild(extG[0],g);
};
最佳答案
正如我在评论中指出的,在将 SVG 作为 DOM 对象获取之前,您不能在 SVG 上使用常规 Dom 方法。
最好的方法是:
var svg=httpresponse.getDocumentElement();
var g=svg.getElementsByTagName('g');
变量 g
将包含 g
元素的实时集合。
关于javascript - xmlHttpRequest 忽略 SVG 中的 g 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39541670/