简体   繁体   English

如何使用Javascript修改SVG标签中的图像标签?

[英]How to Amend an image tag in an SVG tag using Javascript?

How would you go about amending an image tag within an SVG using Javascript?您将如何使用 Javascript 修改 SVG 中的图像标签?

So I have an image stored in a SVG, like so:所以我有一个存储在 SVG 中的图像,如下所示:

<svg height="666px" width="666px" viewBox="0 0 600 600">
 <image id="changingImage" href="phone.png" x="69.0802" y="344.9714" height="28" width="28"></image>
</svg>

So the suggestion I got from online and tried in my script was grabbing the ID and updating the source like so:所以我从网上得到并在我的脚本中尝试的建议是抓取 ID 并更新源代码,如下所示:

document.getElementById("changingImage").src = "phone2.png";

That didn't work, so I thought about it a bit and realized that the image tags in SVG don't use SRC, they use HREF.那行不通,所以我想了一下,意识到SVG中的图像标签不使用SRC,它们使用HREF。 So I tried the following, but it still didn't work:所以我尝试了以下方法,但仍然无效:

document.getElementById("changingImage").href = "phone2.png";

Anyone know how to amend images within an SVG using javascript, or got any ideas about what I could try?任何人都知道如何使用 javascript 修改 SVG 中的图像,或者对我可以尝试的方法有任何想法?

I'd like to post the answer with the syntax for anyone who might have the same problem.我想为可能遇到相同问题的任何人发布带有语法的答案。 The suggestion from user @enxaneta worked, using setAttribute .来自用户@enxaneta的建议使用setAttribute起作用。 Here's the syntax based on the example above.这是基于上述示例的语法。

document.getElementById("changingImage").setAttribute("href", "phone2.png");

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

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