为什么SVG使用javascript创建的元素没有显示?

bok*_*kan 6 javascript svg

我的文档中有一个SVG,我用这样的javascript添加一个符号:

var myScene =document.getElementById('myScene');
var useSVG = document.createElement('use');
useSVG.setAttribute('xlink:href','spriteSheet.svg#mySymbol');
useSVG.setAttribute('x','10');
useSVG.setAttribute('y','30');
useSVG.setAttribute('width','10');
useSVG.setAttribute('height','10');
myScene.appendChild(useSVG);
Run Code Online (Sandbox Code Playgroud)

符号未显示,而生成的代码与正确显示的HTML中编写的另一个节点完全相同.

调试器中显示的代码:

<svg id="myScene" width="200px" height="200px">
    <use xlink:href="spriteSheet.svg#mySymbol" x="5" y="50" width="10" height="10"></use>
    <!-- this one was in html, it is visible -->
    <use xlink:href="spriteSheet.svg#mySymbol" x="10" y="30" width="10" height="10"></use>
    <!-- this one is added with javascript. it is not displayed -->
</svg>
Run Code Online (Sandbox Code Playgroud)

Pau*_*eau 10

您需要使用它createElementNS()来创建SVG元素.基本createElement()创建HTML命名空间中的元素.所以你基本上一直在创造<html:use>元素而不是元素<svg:use>.

var myScene =document.getElementById('myScene');
var useSVG = document.createElementNS('http://www.w3.org/2000/svg', 'use');
useSVG.setAttributeNS('http://www.w3.org/1999/xlink','href','spriteSheet.svg#mySymbol');
useSVG.setAttribute('x','10');
useSVG.setAttribute('y','30');
useSVG.setAttribute('width','10');
useSVG.setAttribute('height','10');
myScene.appendChild(useSVG);
Run Code Online (Sandbox Code Playgroud)

在这里演示

更新

我刚刚意识到你的代码存在第二个问题.您正在使用外部引用href(它在另一个文件中引用一个符号).IE似乎不支持外部引用.

我在这里找到了更多信息和可能的解决方法:http://css-tricks.com/svg-use-external-source/