繁体   English   中英

更改 xlink:href 的<image>在 svg 中,通过经典<a>链接</a>

[英]change the xlink:href of an <image> in a svg, through a classic <a> link

我的网页中有一个 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。

谢谢!

您需要将 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 仍然不支持它。

除了 Robert Longson 的回答之外,如果您通过 js 而不是 html5 设置值,您应该只使用正确的命名空间设置href而不是xlink:href

应该这样设置:

setAttributeNS('http://www.w3.org/1999/xlink', 'href', url);

xlink:href贬值了

这个 JavaScript 方法现在有效:

….setAttribute('href', url);

显然,带双引号的"href"也可以。

这将在每次单击时更改图像。
如果需要使用 click 事件,则需要使用 div 容器。
否则,您可以将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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM