如何使用 SVG 和 Javascript 创建可点击的形状?

How to create a clickable shape with SVG and Javascript?

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset='UTF-8'>
  <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
  <script src='draw.js'></script>
</head>

<body>
  <svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="200"></svg>
</body>

</html>

draw.js

function draw() {
    var svg = document.getElementsByTagName('svg')[0];
    var svgNS = svg.namespaceURI;

    var rect = document.createElementNS(svgNS,'rect');
    rect.setAttribute('x',5);
    rect.setAttribute('y',5);
    rect.setAttribute('width',100);
    rect.setAttribute('height',36);
    rect.setAttribute('fill','#95B3D7');

    var link = document.createElement('a');
    link.setAttribute('xlink:href', 'http://www.google.com');
    link.appendChild(rect);
    svg.appendChild(link);
}

$( document ).ready( draw );

生成的HTML看起来是正确的,但是矩形没有出现:

<a xlink:href="http://www.google.com"> <rect x="5" y="5" width="100" height="36" fill="#95B3D7"></rect> </a>

事实上,当粘贴到 HTML 文件中时,生成的 HTML 确实有效。那么,使用 SVG、Javascript 和链接的浏览器是否有一些限制?

使用 Chrome 39.

您需要创建一个 SVG link 元素而不是 html link 元素,即在 SVG 命名空间

var link = document.createElementNS(svgNS, 'a');
link.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'http://www.google.com');

你做对了矩形本身!