2016-05-12 102 views
2

我需要创建一个使用只有JavaScript这样的结构:创建SVG元素通过JavaScript

<svg> 
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#circle"></use> 
</svg> 

但我有创造xmlns:xlink属性的麻烦。这里是我的js代码:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); 
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); 
// throws error here 
use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink'); 
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#circle'); 
svg.appendChild(use); 

如果我评论字符串设置xmlns:xlink所有工作良好,使SVG上面一样,但没有xmlns:xlink

我看到很多类似于我的问题,但他们没有解决我的问题。

+0

@RobertLongson,我想这个,但我们如何设置'xmlns:xlink'属性? – cassln

+0

@罗伯特朗松,哇,你说得对!现在所有的工作,看起来很好。你可以将你之前的评论格式化为分享你知识的问题(它会更明显)? – cassln

回答

1

关于

use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink'); 

你并不需要这一行,实际上它是无效的。

如果要在XML文档中创建元素/属性,并且在HTML中创建元素时不需要,则使用createElementNS创建元素或使用setAttributeNS创建属性时会自动设置xml属性文件。

0

这里,我们去:

// "circle" may be any tag name 
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 

// Set any attributes as desired 
shape.setAttribute("cx", 25); 
shape.setAttribute("cy", 25); 
shape.setAttribute("r", 20); 
shape.setAttribute("fill", "green"); 

// Add to a parent node; document.documentElement should be the root svg element. 
// Acquiring a parent element with document.getElementById() would be safest. 
document.documentElement.appendChild(shape); 
+0

我需要在不编辑HTML的情况下执行此操作。而创建圈子我也不需要。只需使用。 – cassln

+1

@cassln,我编辑了我的解决方案;) – praguan

+0

此代码仍然与问题不匹配。 – cassln