Dynamic creation of SVG links in JavaScript

梦想与她 提交于 2019-11-29 07:27:23

Only an <a> can be a link so adding an xlink:href attribute to a <rect> element will have no effect.

You need to use setAttributeNS which you say doesn't work but it does for me so perhaps there was some other issue.

This example works for me:

var svgElement = document.getElementById ("svgTag");

var link = document.createElementNS("http://www.w3.org/2000/svg", "a");
link.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', "page2.html");
svgElement.appendChild(link);

var box = document.createElementNS("http://www.w3.org/2000/svg", "rect");
box.setAttribute("x", 30); 
box.setAttribute("y", 30);
box.setAttribute("width", 200);
box.setAttribute("height", 50);
box.setAttribute("fill", "blue");
link.appendChild(box);
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="svgTag">
</svg>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!