How to change div background color on button click?(如何在按钮单击时更改 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();">
<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>
推荐答案
在 html 标签上使用 id 时要小心,因为它会使用 id 进行自动 var 声明代码>.因此,您将使用指向 <input> 的 btnReset 覆盖 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" 或函数btnReset() 名称!
Solution 1: change the id="btnReset" or the function btnReset() name!
解决方案 2:将您的 <script> 移动到文档的末尾(就在 </body> 结束标记之前,因此您的函数会覆盖自动声明的变量.
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 背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在按钮单击时更改 div 背景颜色?
基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
