我正在尝试向JS的SVG元素添加xlink:href
属性,但是它不起作用。
这是我的代码:
test.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>
test.js:
function setupSvgLink() {
var svg = document.getElementById("test-svg").contentDocument;
var waldo = svg.getElementById("waldo");
waldo.setAttribute("xlink:href", "waldo.html");
}
test.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/