通过经典的<a>链接更改SVG中<image>的xlink:href

11

我在网页中有一个SVG(我使用PHP):

<svg width="500px" height="500px" xml:lang="fr"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<image width="500" height="500" xlink:href="img1.jpg" opacity="0.35" />
</svg>

我希望能够在点击链接时(而无需重新加载网页),更改xlink:href变量,类似于:

<a href=#" onclick="changexlinkhref(img2.jpg)">change with img2</a>

然而,我想知道JavaScript函数changexlinkhref(img){}的代码是什么?

目前,我的项目中没有使用JQuery。

谢谢!

4个回答

17

你需要用单引号将img2.jpg参数括起来。如果页面上只有一个图像元素,那么应该可以使用以下代码:

function changexlinkhref(value) {
  document.querySelector("image").setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', value);
}

现在大多数浏览器也支持null命名空间中的href,这导致了更简单的写法。

function changexlinkhref(value) {
  document.querySelector("image").setAttribute('href', value);
}

尽我所知,Inkscape和Batik仍然不支持它。


4

xlink:href 已经过时

这个 JavaScript 方法是现在可用的:

….setAttribute('href', url);

显然,带有双引号的"href"也可以起作用。

4
除了Robert Longson的回答之外,如果您是通过js而不是html5设置值,则应该使用正确的命名空间仅设置href而不是xlink:href。应该像这样设置:
setAttributeNS('http://www.w3.org/1999/xlink', 'href', url);

0

每次被点击时,这将改变图像。
如果您需要使用点击事件,则需要使用

容器。
否则,您可以将 onclick 直接分配给<svg>

<div id="d0"  onclick="next(0);">
 <svg xmlns="http://www.w3.org/2000/svg" width="154" height="205" ">
  <image x="0" y="0" width="154" height="205" href="photo.webp"/>
 </svg>
</div>

<script>
var pointer = 0;
var image = [];
var img = {0:['image0.webp','image1.webp','image2.webp','image3.webp','photo.webp]};
image[id] = document.getElementById('s' + id);

function next(id){
  image[id].setAttribute('href',img[id][pointer++]);
  if (pointer == 4){pointer = 0;}
}
</script>

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