繁体   English   中英

通过点击事件更改div的背景颜色

[英]Changing background color of div through click event

我已经完成了Javascript代码学院的学习。 我现在正在练习我的普通JS技能。

我正在尝试构建一个非常简单的代码,每次单击按钮时都会更改div的背景(我意识到我可以直接通过ID选择div,但是我使用的是不同的选择器类型和方法,因此我可以习惯它们)

 document.getElementById("changeColor").addEventListener("click", function() { var div = document.getElementById("child").parentNode; var random = Math.floor(Math.random() * colors.length); var colors = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine"]; div.style.backgroundColor = colors[random]; }) 
 <div id="example" style="width: 500px; height: 200px; border: solid black 1px; padding: 10px;"> <p id="child">This is just a quick test</p> </div> <button id="changeColor">Change Color</button> 

您的colors变量在第4行中进行了初始化,并且您尝试过在一行中对其进行访问。

您只需切换两条线,它将起作用:

 document.getElementById("changeColor").addEventListener("click", function(){ var div = document.getElementById("child").parentNode; var colors = ["AliceBlue","AntiqueWhite","Aqua","Aquamarine"]; var random = Math.floor(Math.random() * colors.length); div.style.backgroundColor = colors[random]; }) 
 <div id="example" style="width: 500px; height: 200px; border: solid black 1px; padding: 10px;" > <p id="child">This is just a quick test</p> </div> <button id="changeColor">Change Color</button> 

暂无
暂无

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

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