我可以改变背景颜色红色,蓝色,以及绿色, 但是当我单击重置按钮时,我在 Chrome(浏览器)中收到错误:
btnReset 不是函数,
当我点击“重置”按钮时,如何使所有div变为空白?
function btnRed() {
document.getElementById("Div1").style.backgroundColor="Red";
}
function btnGreen() {
document.getElementById("Div2").style.backgroundColor="Green";
}
function btnBlue() {
document.getElementById("Div3").style.backgroundColor="Blue";
}
function btnReset() {
document.getElementById("Div1").style.backgroundColor="Black";
document.getElementById("Div2").style.backgroundColor="white";
document.getElementById("Div3").style.backgroundColor="white";
}
#Div1
{
z-index: -2;
border: 1px solid black;
height: 300px;
width: 400px;
}
#Div2
{
z-index: -1;
border: 1px solid black;
width: 300px;
height: 200px;
margin: 50px 0 0 50px;
}
#Div3
{
border: 1px solid black;
width: 200px;
height: 150px;
margin: 23px 0 0 47px;
}
#DivBtn
{
margin-top: 30px;
}
<div id="Div1">
<div id="Div2">
<div id="Div3">
</div>
</div>
</div>
<div id="DivBtn"> <input type="button" id="btnR" value="Red" onclick="btnRed();">
<input type="button" id="btnG" value="Green" onclick="btnGreen();">
<input type="button" id="btnB" value="Blue" onclick="btnBlue();">
<input type="button" id="btnReset" value="Reset" onclick="btnReset()">
</div>
最佳答案
使用id
时要小心在 html 标签上,因为它使用 id
进行自动 var 声明。因此,您正在覆盖 btnReset
功能与 btnReset
指向<input>
.
解决方案 1:更改 id="btnReset"
或function btnReset()
名字!
解决方案 2:移动您的 <script>
到文档的末尾(就在 </body>
结束标记之前,因此您的函数会覆盖自动声明的 var。
关于javascript - 如何在单击按钮时更改 div 背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703109/