用javascript替换多个图像中的一个

时间:2013-06-14 13:34:53

标签: javascript image replace

我有多张相同的图片。当我点击其中一个img需要更换。我有JS脚本:

var newsrc = "slide_down";
function changeImage() {
    if ( newsrc == "slide_down" ) {
        document.images["pic"].src = "img/slide_up.png";
        document.images["pic"].alt = "slide_up";
        newsrc  = "slide_up";
    }
    else {
        document.images["pic"].src = "img/arrow.png";
        document.images["pic"].alt = "slide_down";
        newsrc  = "slide_down";
    }
}

但是当我按下第二个img时,总是第一个被替换。请帮忙。 图片的Html代码为<img src="img/arrow.png" alt="slide_up" class="head" id="pic" onclick="changeImage()">

1 个答案:

答案 0 :(得分:2)

尝试

var newsrc = "slide_down";
function changeImage() {
    if ( newsrc == "slide_down" ) {
       this.src = "img/slide_up.png";
        this.alt = "slide_up";
        newsrc  = "slide_up";
    }
    else {
        this.src = "img/arrow.png";
        this.alt = "slide_down";
        newsrc  = "slide_down";
    }
}