繁体   English   中英

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

[英]How to change div background color on button click?

我可以更改背景颜色红色、蓝色和绿色,但是当我单击“重置”按钮时,Chrome(浏览器)出现错误:

btnReset 不是 function,

单击“重置”按钮时如何使所有 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();"> &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>

要小心,当你使用id在html标签,因为它使用使得自动变种声明id 因此,您将使用指向<input>btnReset覆盖btnReset函数。

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

解决方案2:将<script>移动到文档末尾(恰好在</body> end标记之前),因此您的函数将覆盖自动声明的var。

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

function btnRed() {
  document.getElementById("Div1").style.backgroundColor="Red";
}
function btnGreen() {
  document.getElementById("Div1").style.backgroundColor="Green";
}
function btnBlue() {
  document.getElementById("Div1").style.backgroundColor="Blue";
}
function btnReset() {
  document.getElementById("Div1").style.backgroundColor="Black";
  document.getElementById("Div1").style.backgroundColor="white";
  document.getElementById("Div1").style.backgroundColor="white";
}

#Div1
{ 
  border: 1px solid black;
  height: 300px;
  width: 400px;
}




<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM