繁体   English   中英

如何更改onClick事件上其他按钮的图像?

[英]How to change image of other buttons on onClick event?

我又来了一个问题。

我有四个按钮,当我单击按钮一时,它会将按钮图像从旧图像更改为新图像,现在可以更改图像,但是如果我按按钮2,则按钮2的图像会更改,但是按钮一的图像是相同的,即新图片。 我希望它还原为旧图像。 这是代码:

<input type="image" id="start" src="buttonred.png" width="50px" height="50px" onClick= "this.src='buttonblue.png'"/>
         <input type="image"  id="stop" src="buttonred.png" width="50px" height="50px" onClick="this.src='buttonblue.png'"/>
          <input type="image"  id="slow" img src="buttonred.png" width="50px" height="50px" onClick="this.src='buttonblue.png'"/>
           <input type="image" id="fast" img src="buttonred.png" width="50px" height="50px" onClick="this.src='buttonblue.png'"/>

未经测试,但是您正在寻找这样的东西:

(function () {
    var elems = document.getElementsByTagName("input");
    for (var i = 0; i < elems.length; i++) {
        elems[i].addEventListener("click", function () {
            for (var a = 0; a < elems.length; a++) {
                elems[a].src = "buttonred.png";
            }
            elems[i].src = "buttonblue.png";
        });
    }
})()

此处的关键是在您单击的图像更改之前,让您的功能将所有图像重置为原始图像。

在记事本中输入并进行测试。

它本质上是搜索buttonred字符串值,并将其替换为buttonblue,反之亦然。

<input type="image" id="start" src="buttonred.png" width="50px" height="50px" onClick="colorChange(this.id)"/>
<input type="image" id="stop" src="buttonred.png" width="50px" height="50px" onClick="colorChange(this.id)"/>
<input type="image" id="slow" src="buttonred.png" width="50px" height="50px" onClick="colorChange(this.id)"/>
<input type="image" id="fast" src="buttonred.png" width="50px" height="50px" onClick="colorChange(this.id)"/>

<script>

function colorChange(id) {
    var btn = document.getElementById(id);

    if (btn.src.match(/buttonred/gi) != null) {
        btn.src = btn.src.replace("buttonred.png","buttonblue.png");
    }
    else {
        btn.src = btn.src.replace("buttonblue.png","buttonred.png");
    }
}

</script>

暂无
暂无

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

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