2011-05-20 3 views
4

Comment créer une ancre SVG via JavaScript? S'il vous plaît voir la section pertinente et un exemple de spec. Comment puis-je convertir cet exemple JavaScript (essentiellement, comment générer dynamiquement l'élément conteneur a de sorte que lorsque je clique sur l'ellipse, il navigue loinCréer un élément d'ancrage SVG par programme?

<?xml version="1.0"?> 
<svg width="5cm" height="3cm" viewBox="0 0 5 3" version="1.2" baseProfile="tiny" 
    xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 

    <title>Example 17_01</title> 
    <desc>A simple link on an ellipse.</desc> 
    <rect x=".01" y=".01" width="4.98" height="2.98" 
     fill="none" stroke="blue" stroke-width=".03"/> 
    <a xlink:href="http://www.w3.org/"> 
    <ellipse cx="2.5" cy="1.5" rx="2" ry="1" 
      fill="red" /> 
    </a> 
</svg> 

Répondre

2

en utilisant ci-dessous ma fonction, il est aussi facile que cela:

// Find the first SVG element 
var svg = document.getElementsByTagName('svg')[0]; 
var a = createOn(svg,'a',{'xlink:href':'http://www.w3.org/'}); 
createOn(a,'ellipse',{cx:2.5,cy:1.5,rx:1,ry:1,fill:'red'}); 

function createOn(root,name,attrs,text){ 
    var doc = root.ownerDocument, 
     svg = root.ownerSVGElement || root; // In case the root _is_ the <svg> 
    var svgNS = svg.getAttribute('xmlns'); 
    var el = doc.createElementNS(svgNS,name); 
    for (var attr in attrs){ 
    if (!attrs.hasOwnProperty(attr)) continue; 
    var parts = attr.split(':'); 
    if (parts[1]) el.setAttributeNS(
     svg.getAttribute('xmlns:'+parts[0]),parts[1],attrs[attr] 
    ); 
    else el.setAttributeNS(null,attr,attrs[attr]); 
    } 
    if (text) el.appendChild(document.createTextNode(text)); 
    return root.appendChild(el); 
} 

Si vous avez déjà l'ellipse et wa nt pour l'envelopper, puis créez l'élément 'a' et:

// Get a reference to the ellipse however you like 
var ellipse = document.getElementsByTagName('ellipse')[0]; 

// Put the anchor node immediately preceding the ellipse 
ellipse.parentNode.insertBefore(a,ellipse); 

// Move the ellipse to be a child of the anchor 
a.appendChild(ellipse); 
6

Ceci est juste DOM de base.

var xlinkNS="http://www.w3.org/1999/xlink", svgNS="http://www.w3.org/2000/svg"; 

var a = document.createElementNS(svgNS, "a"); 
a.setAttributeNS(xlinkNS,"href","http://www.w3.org/"); 

var ellipse = document.createElementNS(svgNS, "ellipse"); 
ellipse.setAttributeNS(null,"cx","2.5"); 
ellipse.setAttributeNS(null,"cy","1.5"); 
ellipse.setAttributeNS(null,"rx","2"); 
ellipse.setAttributeNS(null,"ry","1"); 
ellipse.setAttributeNS(null,"fill","red"); 

a.appendChild(ellipse); 
document.documentElement.appendChild(a); 
Questions connexes