使用Javascript切换图像src属性 [英] Toggle image src attribute using Javascript
问题描述
我正在尝试使用Javascript更改HTML图像 src
。我有两个图像Plus.gif和Minus.gif.I已插入HTML img
标签并编写了一个Javascript函数来更改图像 src 单击code>。
I am trying to change the HTML image src
using Javascript. I have two images Plus.gif and Minus.gif.I have inserted HTML img
tag and have written a Javascript function to change the image src
when clicked.
问题是我想在用户点击图片时再将其更改回来。
例如,当页面加载时, Plus.gif
显示,当用户点击它时,图像变为 Minus.gif
。
Problem is that I want to change it back again when user clicks on the image.
For example when the page is loaded the Plus.gif
shows and when user clicks on it the image it changes to Minus.gif
.
我希望如此,当图片 Minus.gif
并且用户点击它时,应该将其更改为 Plus.gif
。
I want it so, when the image is Minus.gif
and user clicks on it this should be changed to Plus.gif
.
这是我的Javascript功能:
Here is my Javascript function:
<script language="javascript" type="text/javascript">
function chngimg() {
var img = document.getElementById('imgplus').src; //= 'Images/Minus.gif';
if (img) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
} else if (!img) {
document.getElementById('imgplus').src = 'Images/Plus.gif';
alert(img);
}
}
</script>
图片标签:
<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()" />
推荐答案
查看我为使其工作所做的更改
See the changes I made to make it working
<script language="javascript" type="text/javascript">
function chngimg() {
var img = document.getElementById('imgplus').src;
if (img.indexOf('Plus.gif')!=-1) {
document.getElementById('imgplus').src = 'Images/Minus.gif';
}
else {
document.getElementById('imgplus').src = 'Images/Plus.gif';
}
}
</script>
<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()" />
希望能解决你的问题。
这篇关于使用Javascript切换图像src属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!