如何在单击按钮时更改div背景颜色? [英] How to change div background color on button click?

查看:177
本文介绍了如何在单击按钮时更改div背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can change the background color Red, Blue, as well as Green, but when I click the Reset button I get an error in Chrome(browser):

btnReset不是函数,

btnReset is not a function,

当我单击重置"按钮时如何将所有div留空?

How to make all div blank when I click Reset button?

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>

推荐答案

在html标记上使用id时要小心,因为它会使用id进行自动var声明.因此,您要用btnReset指向<input>覆盖btnReset函数.

Be careful when you're using id on the html tags, because it makes an automatic var declaration using the id. So, you're overriding the btnReset function with the btnReset pointing to the <input>.

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

Solution 1: change the id="btnReset" or the function btnReset() name!

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

Solution 2: move your <script> to the end of the document (just before the </body> end tag, so your function overrides the automatic declarated var.

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

这篇关于如何在单击按钮时更改div背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆