如何在单击按钮时更改 div 背景颜色?

0 html javascript onclick

我可以更改背景颜色红色、蓝色和绿色,但是当我单击“重置”按钮时,我在 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";
}
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
<div id="Div1">
  <div id="Div2">
    <div id="Div3">

    </div>
  </div>
</div>

<div id="DivBtn"> <input type="button" id="btnR" value="Red" onclick="btnRed();"> &nbsp;&nbsp;
  <input type="button" id="btnG" value="Green" onclick="btnGreen();">&nbsp;&nbsp;
  <input type="button" id="btnB" value="Blue" onclick="btnBlue();">&nbsp;&nbsp;
  <input type="button" id="btnReset" value="Reset" onclick="btnReset()">
</div>
Run Code Online (Sandbox Code Playgroud)

smi*_*oli 5

在 html 标签上使用时要小心id,因为它会使用id. 因此,您将btnReset通过btnReset指向<input>.

解决方案1:更改id="btnReset"function btnReset()名称!

解决方案 2:将您的函数移动<script>到文档的末尾(就在</body>结束标记之前,这样您的函数就会覆盖自动声明的 var。

其他信息:http://www.2ality.com/2012/08/ids-are-global.html