2013-10-10 64 views
0

我试图创建一个svg图像和文本对象,这两个对象都需要命名空间来设置xlink:href和xml:space属性。我试着下面的代码,没有运气创建这些对象,所以我可以将它们添加到屏幕上:使用名称空间创建SVG对象

function createSVGNode(node) { 
    var svg = document.createElementNS('http://www.w3.org/1999/xlink', 'svg'); 
    var ns2 = null; 
    if(node.nodeName == 'image') { ns2 = 'http://www.w3.org/1999/xlink'; } 
    var shape = document.createElementNS(ns2, node.nodeName); 
    svg.appendChild(shape); 
    var ns = null; 
    for(var attr = 0; attr < node.attributes.length; attr++) { 
     if(node.nodeName == 'image' && node.attributes[attr].nodeName == 'xlink:href') { 
      ns = 'http://www.w3.org/1999/xlink'; 
     } 
     if(node.nodeName == 'text' && node.attributes[attr].nodeName == 'xml:space') { 
      ns = 'http://www.w3.org/XML/1998/namespace'; 
     } 
     shape.setAttributeNS(ns, node.attributes[attr].nodeName, node.attributes[attr].nodeValue); 
     ns = null; 
    } 
    if(node.childNodes.length == 1) shape.appendChild(node.childNodes[0]); 
    return shape; 
} 

我敢肯定,我会对此更难比我需要,但一切工作直到我不得不处理图像和文本对象。

回答

0

SVG元素都在SVG命名空间

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); 
var shape = document.createElementNS('http://www.w3.org/2000/svg', node.nodeName); 
svg.appendChild(shape); 
var ns = null; 
for(var attr = 0; attr < node.attributes.length; attr++) { 
    if(node.nodeName == 'image' && node.attributes[attr].nodeName == 'xlink:href') { 
     ns = 'http://www.w3.org/1999/xlink'; 
    } 
    if(node.nodeName == 'text' && node.attributes[attr].nodeName == 'xml:space') { 
     ns = 'http://www.w3.org/XML/1998/namespace'; 
    } 
    shape.setAttributeNS(ns, node.attributes[attr].nodeName, node.attributes[attr].nodeValue); 
    ns = null; 
} 
if(node.childNodes.length == 1) shape.appendChild(node.childNodes[0]); 
return shape; 
+0

不是任何图像对象或文本对象的工作,我做了什么被视为动态标记,看看被给了默认的元素命名空间是什么这些命名空间在我的例子中。 –

+0

可以说我使用http://www.w3.org/1999/xlink名称空间添加了一个属性,就像在我的示例中,我使用http://www.w3.org/1999/xlink添加了图像对象名称空间是足够聪明的DOM来创建图像对象,如