如何通过编程创建SVG锚点元素?

4
我如何通过JavaScript创建SVG锚点?请参见相关章节和规范中的示例。我该如何将此示例转换为JavaScript(基本上,如何动态生成容器元素a,以便当我单击椭圆时,它会导航离开。
<?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个回答

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

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

如果您已经拥有椭圆形,并想要将其包装起来,则需要创建“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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接