簡體   English   中英

如何更改 HTML 中的按鈕背景顏色?

[英]How can i change a button background color in HTML?

我正在嘗試使用條件更改按鈕的背景顏色:如果顏色為“紅色”,它將變成“綠色”並反轉。 我嘗試編寫此代碼,但沒有任何更改。

 function changeColor() { var f = document.getElementById(food).value; switch (f) { case "morning": var m = document.getElementsByName(FoodM); if (m.style.backgroundColor == "red") { m.style.backgroundColor = "green"; } else { m.style.backgroundColor = "red"; } break; case "evning": var e = document.getElementByName(FoodE) if (e.style.backgroundColor == "red") { e.style.backgroundColor = "green"; } else { e.style.backgroundColor = "red"; } break; } }
 <td class="auto-style1" style=" width: 88px"> <input id="food" onclick='changeColor()' name="FoodM" type="button" value="morning" style="width: 88px; height: 75px; background-color:red;font-size:medium" /></td> <td></td> <td class="auto-style1" style=" width: 88px"> <input id="food" onclick='changeColor()' name="FoodE" type="button" value="evning" style="width: 88px; height: 75px; background-color:green;font-size:medium" /></td> </tr> </table> <br>

我究竟做錯了什么?

謝謝你。

document.getElementsByName的值應該在 " " -s 之間。 喜歡

var m = document.getElementsByName("FoodM")[0]

此外, document.getElementsByName返回一個數組,因此在您只有 1 個具有 FoodM 名稱的元素時,您應該通過在末尾添加[0]來返回數組的第一個元素。

id 'food' 在文檔中出現不止一次。 ID 應該是唯一的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM