gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:10:24 25 4
gpt4 key购买 nike

我可以改变背景颜色红色,蓝色,以及绿色,但是当我单击重置按钮时,我在 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();"> &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 进行自动 var 声明。因此,您正在覆盖 btnReset功能与 btnReset指向<input> .

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

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

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

关于javascript - 如何在单击按钮时更改 div 背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com