2011-05-20 87 views
4

如何通過JavaScript創建SVG錨點?請參閱spec中的相關部分和示例。如何轉換這個例子中的JavaScript(基本上,如何動態生成的容器元素a所以,當我點擊的橢圓,它導航離開以編程方式創建SVG錨點元素?

<?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> 

回答

2

使用我下面的功能,它是那麼容易,因爲這樣的:

// 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); 
} 

如果你已經有橢圓和WA nt來包裹它,然後創建'a'元素並且:

// 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

這僅僅是基本的DOM:

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);