2014-10-08 66 views
0

我在這裏再次出現問題。如何更改onClick事件上其他按鈕的圖像?

我有四個按鈕,當我點擊按鈕之一時,它將按鈕圖像從舊圖像更改爲新圖像現在,圖像被更改,但如果我按下按鈕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'"/> 
+0

我建議您設置一個功能,將所有te圖像重置爲第一個圖像,並在更改點擊圖像之後。 – J261 2014-10-08 18:39:18

回答

1

在記事本中輸入並測試過。

它實質上是搜索字符串值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> 
+0

有一個小問題,它不會改變其他按鈕的按鈕顏色,它只是改變自己的顏色。 – 2014-10-08 20:02:45

+0

請幫助!您的代碼只適用於一個按鈕。其他按鈕不受影響 – 2014-10-08 20:36:08

+0

您使用的是什麼瀏覽器?我在firefox和chrome上測試過它,它適用於所有按鈕。 – AJY 2014-10-09 21:15:14

1

未經檢驗的,但這樣的事情是你在找什麼:

(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"; 
     }); 
    } 
})() 

這裏的關鍵是讓你的功能重置所有圖像的回到原來的在被點擊的那個之前改變。