将SVG节点导入到IE9中的另一个文档中 [英] Import SVG node into another document in IE9

查看:100
本文介绍了将SVG节点导入到IE9中的另一个文档中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用XHR提取SVG文档后,我需要将responseXML文档中的一部分添加到当前文档中.使用此代码可在Safari/Chrome/FireFox上使用,但不适用于IE9:

After fetching an SVG document using XHR I need to append a portion of it from the responseXML document into the current document. Using this code works on Safari/Chrome/FireFox, but does not work on IE9:

var xhr = new XMLHttpRequest;
xhr.open('get','stirling4.svg',true);
xhr.onreadystatechange = function(){
  if (xhr.readyState != 4) return;
  var g = xhr.responseXML.getElementsByTagName('g')[2];
  var p = document.getElementsByTagName('path')[0];
  p.parentNode.insertBefore(document.importNode(g,true),p);
};
xhr.send();

IE9在调用importNode时引发脚本错误:

IE9 throws a script error when calling importNode:

SCRIPT16386:不支持此类接口

SCRIPT16386: No such interface supported

我发现一个问题在其他人报告类似问题的地方.您可以在我的网站上看到一个实时示例. (SVG文件本身显示为分形,使用XHR提取另一个SVG文件,使用一种技术来手动导入一个节点,然后尝试使用importNode导入另一个节点.在一个Chrome,Safari或Firefox中,您会看到两个灰色菱形导入到文档中,而在IE9上,只有第一个菱形可用.)

I found a question where someone else reports a similar problem. You can see a live example of this problem on my website. (The SVG file itself displays a fractal, uses XHR to fetch another SVG file, uses one technique to manually import one of the nodes and then attempts to use importNode to import another node. One Chrome, Safari, or Firefox you see two grey diamonds imported into the document, while on IE9 only the first diamond works.)

如何使importNode与IE9兼容?

推荐答案

这是一种变通方法,它通过使用自定义函数递归克隆节点的所有部分而不是使用importNode来手动导入"节点.在我的示例页面上使用此代码来导入两个形状之一.

Here's a workaround solution that manually 'imports' the node by using a custom function to recursively clone all portions of it instead of using importNode. This code is used on my example page to import one of the two shapes.

var xhr = new XMLHttpRequest;
xhr.open('get','stirling4.svg',true);
xhr.onreadystatechange = function(){
  if (xhr.readyState != 4) return;
  var g = xhr.responseXML.getElementsByTagName('g')[2];
  var p = document.getElementsByTagName('path')[0];
  p.parentNode.insertBefore(cloneToDoc(g),p);
};
xhr.send();

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;
}

这篇关于将SVG节点导入到IE9中的另一个文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆