javascript - 如何使用 addEventListener 更改 div 的颜色
问题描述
为什么当我单击具有类圆形颜色的 div 时,颜色不会改变?另外,我怎样才能让它改变onclick
?
var round = document.querySelector(".round");
round.addEventListener("click", function() {
round.style.backroundColor = "blue";
});
.round {
height: 25px;
width: 25px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
}
<div class="round"></div>
<div class="round"></div>
<div class="round"></div>
<div class="round"></div>
<div class="round"></div>
<div class="round"></div>
解决方案
第一个原因是你没有backgroundColor
正确拼写。
但是,即使是固定的,也只有第一个圆圈可以工作,因为你使用querySelector()
了 ,它在第一个匹配之后停止寻找匹配并且只返回那个匹配。
您可以使用querySelectorAll()
,它找到所有匹配的元素并将它们作为节点列表返回。但是随后您将不得不遍历节点列表并在每个节点上附加事件处理程序。这肯定会奏效,但更好的方法是利用事件冒泡click
并在更高级别进行监听。
此外,与其创建内联样式(以后很难覆盖),不如使用预先存在的 CSS 类并根据需要应用或删除它们element.classList
。下面,我将展示如何在连续点击时打开/关闭颜色。
// Listen for clicks at a higher level that click will bubble up to
document.addEventListener("click", function(event){
// Check to see if a "round" element was the trigger for the event
if(event.target.classList.contains("round")){
// Style the trigger based on adding/removing the pre-existing class
event.target.classList.toggle("highlight")
}
});
.round {
height: 25px;
width: 25px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
}
/* This will be applied or removed as needed */
.highlight {
background-color:blue;
}
<div class="round"></div>
<div class="round"></div>
<div class="round"></div>
<div class="round"></div>
<div class="round"></div>
<div class="round"></div>
推荐阅读
- java - OC4J/Eclipse - 缺少类路径条目 C:\oracle\OC4J10.1.3\j2ee\home\admin.jar
- reactjs - 内容与反应预期参数 accessToken 错误
- wpf - IsMouserOver 上带有触发器的样式仍显示窗口蓝色
- excel - Set password when closing
- android - Android - windowIsTranslucent 使布局跳转到状态栏后面
- python - 如何用布尔值重塑熊猫数据框
- spring-boot - AbstractMessageBrokerConfiguration 类无法打开,因为它不存在
- javascript - 如何通过 ipcRenderer.send() 传递窗口?
- python - python将一列的内容复制到另一列
- variables - 如何在配置单元查询中使用嵌套变量替换