我尝试通过 JS 将 xlink:href
属性添加到 SVG 元素,但它不起作用。
这是我的代码:
测试.html:
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body onload=setupSvgLink()>
<object id="test-svg" type="image/svg+xml" data="test.svg" />
</body>
</html>
测试.js:
function setupSvgLink() {
var svg = document.getElementById("test-svg").contentDocument;
var waldo = svg.getElementById("waldo");
waldo.setAttribute("xlink:href", "waldo.html");
}
测试.svg:
<?xml version="1.0" standalone="no"?>
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="80">
<a id="waldo"><rect x="10" y="10" width="60" height="60" fill="blue"/></a>
</svg>
我正在使用 Firefox 20 对此进行测试。我加载 test.html
,但矩形上没有链接。我已在 Firefox 开发者工具的检查器中检查到 xlink:href 属性确实出现在元素上,但没有链接。
如果我将 xlink:href 属性添加到 SVG 文件中,而不是通过 JS 进行操作,则效果很好。
我做错了什么?
最佳答案
处理 SVG 时,您通常需要使用 element.setAttributeNS
,更改您的函数...
function setupSvgLink() {
var xlinkns="http://www.w3.org/1999/xlink";
var svg = document.getElementById("test-svg").contentDocument;
var waldo = svg.getElementById("waldo");
waldo.setAttributeNS(xlinkns, "href", "waldo.html");
}
关于javascript - 使用 JS 设置 SVG 元素的属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20810578/