所以我有4个按钮。如果我点击其中一个,该按钮的背景颜色应为蓝色。如果没有点击该按钮,我希望颜色保持不变(颜色为红色)。我该怎么做?
目前它仅适用于一个按钮。每当我点击另一个按钮时,它会改变该按钮的颜色,而不是我点击的按钮的颜色。
编辑1: 这是我更新的代码。
function buttonFunction() {
var buttons = new Array("button", "button1", "button2", "button3", "button4");
for (var i in buttons) {
if (onclick = true) {
document.getElementById(buttons[i]).style.backgroundColor = "blue";
}
}
}
<body id="Body">
<!-- Navigation bar setup -->
<header id="Mainheader">
<nav id="Navigation">
<form>
<button type="button" value="submit" class="Button" onclick="buttonFunction()" id="button"><a href="index.html" class="Button-link" >Introduction</a></button>
<button type="button" value="submit" class="Button" onclick="buttonFunction()" id="button"><a href="History-of-astronomy.html" class="Button-link">History of Astronomy</a></button>
<button type="button" value="submit" class="Button" onclick="buttonFunction()" id="button"><a href="Observational-Astronomy.html" class="Button-link" >Observational Astronomy</a></button>
<button type="button" value="submit" class="Button" onclick="buttonFunction()" id="button"><a href="" class="Button-link">More on Astronomy</a></button>
</form>
</nav>
</header>
<!-- Navigation bar setup (complete) -->
答案 0 :(得分:0)
更新点击处理程序功能:
function buttonFunction(btn) {
btn.style.backgroundColor = "blue";
}
将按钮声明更改为:
<button type="button" value="submit" class="Button" onclick="buttonFunction(this)" id="button"><a href="" class="Button-link">More on Astronomy</a></button>
答案 1 :(得分:0)
在onclick函数中传递按钮引用并更改它的样式。
muni
function buttonFunction(el) {
el.style.backgroundColor = "red";
}