[英]Changing background-color of a button using 1 javascript
我想改变按钮的背景颜色。 到目前为止这是我的代码:
<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更改每个按钮的颜色?
<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)"
}
}
尝试这个:-
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)" } }
<input type="button" id="button" value = "button" onclick="setColor(this.id);"/>
您的脚本中存在空间问题,我在脚本中删除了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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.