首页 > 解决方案 > 如何使用 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>

标签: javascripthtmlcss

解决方案


第一个原因是你没有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>


推荐阅读