导入外部SVG(使用WebKit) [英] Importing external SVG (with WebKit)
问题描述
下面的例子适用于Firefox 4,但不适用于Chrome 10:
< svg:svg version =1.1> ;
< svg:use xlink:href =some_file.svg#layer1/>
< / svg:svg>
这是 Chrome / WebKit中的一个已知错误,所以除了尝试寻找解决方法之外,我无能为力。我想过使用 XMLHttpRequest
来获取外部文件并将其插入到 svg
元素中。会造成什么问题吗?有没有更好的方法来做到这一点?
通过XHR获取SVG文档后, xhr.responseXML
属性。由于您无法合法地将节点从一个文档移动到另一个文档,因此您需要将所需的一部分从一个文档导入到目标文档中,然后才能将其用作该文档的一部分。
最简单的方法是使用 document.importNode()
:
var clone = document.importNode(nodeFromAnotherDoc,true);
//现在你可以在文档中插入clone
然而,这不适用于IE9 。为了解决这个问题,你可以使用这个函数递归地重新创建所选文档中的节点层次结构: 您可以看到一个使用XHR获取SVG文档的例子,在我的网站上导入节点: http://phrogz.net/SVG/fetch_fragment.svg The following works in Firefox 4, but not Chrome 10: This is a known bug in Chrome/WebKit, so there's nothing I can do about that except try to find a way to work around it. I thought about using an After you fetch the SVG document via XHR you will have a separate XML document in the The simplest way to do this is to use However, this does not work for IE9. To work around that bug, you can alternatively use this function to recursively recreate a node hierarchy in the document of choice: You can see an example of using XHR to fetch an SVG document and both techniques of importing the node on my website: http://phrogz.net/SVG/fetch_fragment.svg 这篇关于导入外部SVG(使用WebKit)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b $ pre $ 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;
$ / code> <svg:svg version="1.1">
<svg:use xlink:href="some_file.svg#layer1"/>
</svg:svg>
XMLHttpRequest
to grab the external file and insert it into the svg
element. Will that cause any problems? Are there better ways to do it?xhr.responseXML
property. Since you cannot legally move nodes from one document to another, you'll need to import the portion you want from one document into your target document before you can use it as part of that document.document.importNode()
:var clone = document.importNode(nodeFromAnotherDoc,true);
// Now you can insert "clone" into your document
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;
}