2015-12-26 33 views
8

我试图在JS中创建一个SVG元素,然后将其附加到DOM。尽管SVG元素引用了一个符号。我可以使用insertAdjacentHTML方法实现此目的,但不能通过appendChild方法实现。SVG脚本与<symbol>

当使用appendChild时,根据浏览器检查器,所有正确的东西都在DOM上,但它不能正确呈现。任何人都能看到为什么

http://codepen.io/bradjohnwoods/pen/dGpqMb?editors=101

<svg display="none"> 
    <symbol id="symbol--circle--ripple" viewBox="0 0 100 100"> 
    <circle cx="50" cy="50" r="25" /> 
    </symbol> 
</svg> 

<button id="btn"> 
</button> 

<script> 
var btn = document.getElementById('btn'); 

//var myString = '<svg><use xlink:href="#symbol--circle--ripple" width="100" height="100" class="btn--ripple__circle"></use></svg>'; 
//btn.insertAdjacentHTML('afterbegin', myString); 

var svg = document.createElement('svg'); 
var use = document.createElement('use'); 
use.setAttribute("xlink:href", "#symbol--circle--ripple"); 
use.setAttribute("width", "100"); 
use.setAttribute("height", "100"); 
use.classList.add("btn--ripple__circle"); 

svg.appendChild(use); 
btn.appendChild(svg); 
</script> 
+0

'的xmlns:XLink的=“http://www.w3.org/1999/xlink”' – CoderPi

+0

说什么也没做 –

回答

3

使用createElement不能创建SVG元素,必须使用createElementNS在SVG命名空间

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); 
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); 

insertAdjacentHTML调用HTML解析器,奇迹般地修复元素的命名空间来创建它们。

同样,您不能使用setAttribute在xlink命名空间(如xlink:href)中创建属性。你想

setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#symbol--circle--ripple"); 

+0

,做创建SVG元素,以正确的大小,但不instanate符号 –

0

我找到了解决办法,.createElementNS & .setAttributeNS不得不使用。

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); 
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); 
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#symbol--circle--ripple');