通过XHR获取SVG文档后,您将在xhr.responseXML
属性中拥有单独的XML文档。由于您无法合法地将节点从一个文档移动到另一个文档,因此您需要将一个文档所需的部分导入目标文档,然后才能将其作为该文档的一部分使用。
要做到这一点,最简单的方法是使用document.importNode()
:
var clone = document.importNode(nodeFromAnotherDoc,true);
// Now you can insert "clone" into your document
然而,this does not work for IE9。要解决这个bug,您也可以使用此功能选择的文件中递归地重新创建节点层次结构:
function cloneToDoc(node,doc){
if (!doc) doc=document;
var clone = doc.createElementNS(node.namespaceURI,node.nodeName);
for (var i=0,len=node.attributes.length;i<len;++i){
var a = node.attributes[i];
clone.setAttributeNS(a.namespaceURI,a.nodeName,a.nodeValue);
}
for (var i=0,len=node.childNodes.length;i<len;++i){
var c = node.childNodes[i];
clone.insertBefore(
c.nodeType==1 ? cloneToDoc(c,doc) : doc.createTextNode(c.nodeValue),
null
);
}
return clone;
}
您可以看到使用XHR来获取一个SVG文件的例子导入这两种技术和在我的网站节点:http://phrogz.net/SVG/fetch_fragment.svg
在迈克或@Progrog:可以编程方式测试这个'使用'功能没有浏览器嗅探? – 2011-10-07 22:43:39
相关问题 - http://stackoverflow.com/questions/1811116/ie-support-for-dom-importnode – resnyanskiy 2012-03-26 03:13:38