我想更改按钮的背景颜色。 到目前为止,这是我的代码:
<script>
function setColor(btn) {
var property = document.getElementById(btn);
if (property.style.backgroundColor == "rgb(127, 255, 0)") {
property.style.backgroundColor = "rgb(255, 0, 0)"
}
else if(property.style.backgroundColor == "rgb(255, 0, 0)")
{
property.style.backgroundColor = ""
}
else {
property.style.backgroundColor = "rgb(127, 255, 0)"
}
}
</script>
<input type="button" id="button" value = "button" onclick="setColor('button')";/>
这适用于一个按钮。如果我有多个按钮,它只会更改第一个按钮颜色。如何使用此JavaScript更改每个按钮的颜色?
答案 0 :(得分:3)
<input type="button" id="button" value = "button" onclick="setColor(this);"/>
JS:
function setColor(btn) {
if (btn.style.backgroundColor == "rgb(127, 255, 0)") {
btn.style.backgroundColor = "rgb(255, 0, 0)"
}
else if(btn.style.backgroundColor == "rgb(255, 0, 0)")
{
btn.style.backgroundColor = ""
}
else {
btn.style.backgroundColor = "rgb(127, 255, 0)"
}
}
答案 1 :(得分:0)
试试这个: -
function setColor(btn) {
var property = document.getElementById(btn);
if (property.style.backgroundColor == "rgb(127, 255, 0)") {
property.style.backgroundColor = "rgb(255, 0, 0)"
}
else if(property.style.backgroundColor == "rgb(255, 0, 0)")
{
property.style.backgroundColor = ""
}
else {
property.style.backgroundColor = "rgb(127, 255, 0)"
}
}
&#13;
<input type="button" id="button" value = "button" onclick="setColor(this.id);"/>
&#13;
答案 2 :(得分:0)
您的脚本中存在空间问题,我在脚本中删除了rgb颜色的空格并且工作正常
<script>
function setColor(btn) {
var property = document.getElementById(btn);
if (property.style.backgroundColor == "rgb(127,255,0)") {
property.style.backgroundColor = "rgb(255,0,0)"
}
else if(property.style.backgroundColor == "rgb(255,0,0)")
{
property.style.backgroundColor = ""
}
else {
property.style.backgroundColor = "rgb(127,255,0)"
}
}
</script>