我正在尝试加载外部svg文件,然后在其上面写入其他SVG元素。当我这样做时,我在“节点”上收到错误“无法执行'appendChild':文档上只允许一个元素。”当我在Chrome中检查时。
这是HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="mySvg">
<circle cx="40" cy="30" r="15" fill="#FF00FF"
stroke="#000000" stroke-width="2" />
</svg>
<object data="img/drawing.svg" type="image/svg+xml"
align="center" id="svgDrw" height="80vh"></object>
<script type="text/javascript" src="js/problem.js"></script>
</body>
</html>
这是问题.js:
var svgXtraDoc;
var d = document.getElementById("svgDrw");
d.addEventListener("load",function(){
// get the inner DOM
svgXtraDoc = d.contentDocument;
// get the inner element by id
svgRect1 = svgXtraDoc.getElementById("MyRect1");
svgRect2 = svgXtraDoc.getElementById("MyRect2");
}, false);
function addRect() {
var svgRect = document.createElementNS("http://www.w3.org/2000/svg",
"rect");
svgRect.setAttribute("x", 100);
svgRect.setAttribute("y", 100);
svgRect.setAttribute("width", 100);
svgRect.setAttribute("height", 100);
svgRect.style.fill = "red";
// mySvg.appendChild(svgRect);
svgXtraDoc.appendChild(svgRect);
}
document.getElementById("mySvg").addEventListener("click", addRect);
...这里是drawing.svg,剥夺了一些Inkscapy残骸:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
width="29.02857mm"
height="37.092064mm"
viewBox="0 0 102.85714 131.42857"
id="svg2"
version="1.1">
<g
id="layer1"
transform="translate(-205.71428,-218.07649)">
<rect
style="stroke:none;fill-opacity:1;fill:#5eb056"
id="MyRect1"
width="102.85714"
height="131.42857"
x="205.71428"
y="218.07649" />
<rect
style="fill:#000000;stroke:none;fill-opacity:1"
id="MyRect2"
width="42.857143"
height="65.714287"
x="231.42857"
y="252.3622" />
</g>
</svg>
单击圆圈时出现错误:不会出现应出现在双矩形导入图形中的矩形,并且“节点”上的错误消息“无法执行'appendChild':只有一个元素文件允许。“显示在控制台中。
如果我改变这个,那么矩形被添加到包含圆圈的svg中,即通过取消注释“@ mySvg.appendChild(svgRect);”这一行,然后矩形成功出现。
我也知道图形文件已成功加载,因为在其他代码中(为简洁起见,此处未包括)我可以更改该文件中矩形的颜色。所以我似乎可以访问文件中的现有元素,但不能添加元素。
有没有关于外部加载的SVG与内联SVG的内容,我没有考虑到这一点?
最后一件事 - 这是进入Cordova应用程序,所以我想保持它小,所以首选纯JavaScript解决方案。如果必须的话,我会使用JQuery或SnapSVG,但似乎我的需求足够简单,没有外部库就可以做到这一点。
答案 0 :(得分:29)
在我的情况下,DOM抱怨是因为我试图在文档中添加一个孩子:
document.appendChild(myElement);
我通过获取对body标签的引用来解决它:
document.body.appendChild(logger);
答案 1 :(得分:13)
文档的根节点与文档元素之间存在差异。你想要的是<svg>
文档元素,但.contentDocument
可以获得根节点。
根节点是一个层次结构级别。这意味着,<svg>
文档元素位于根节点内,根节点可能只有一个<svg>
子元素。
要获取文档元素,请执行以下操作:
svgXtraDoc = d.contentDocument.documentElement;