2015-12-26 12 views
8

Sto cercando di creare un elemento SVG in JS e quindi aggiungerlo al DOM. L'elemento SVG fa riferimento a un simbolo però. Posso ottenere questo risultato usando il metodo insertAdjacentHTML ma non attraverso il metodo appendChild.Script SVG con <symbol>

Quando si utilizza appendChild, tutti gli elementi corretti si trovano sul DOM in base agli ispettori del browser, ma non sono visualizzati correttamente. Qualcuno può vedere perché?

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

che non ha fatto nulla –

risposta

3

Non è possibile creare elementi SVG usando createElement, è necessario utilizzare createElementNS crearle nel namespace SVG

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

insertAdjacentHTML invoca il parser HTML che fissa magicamente gli spazi dei nomi degli elementi.

Analogamente, non è possibile utilizzare setAttribute per creare attributi nello spazio dei nomi xlink come xlink: href. Si vuole

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

ci

+0

che fa creare l'elemento SVG al formato corretto, ma non instanate il simbolo –

0

ho trovato la soluzione, .createElementNS & .setAttributeNS dovevano essere utilizzati.

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'); 
Problemi correlati