首页 > 解决方案 > 如何使用 addEventListener("click") 更改多个具有相同 id 的 div 的颜色?

问题描述

再会,

我有一个由 9 个方形 div 组成的 CSS 网格,我想为它们添加一个单击事件,以便它们的颜色从浅绿色变为黑色,然后在鼠标离开时变回浅绿色。如果我给每个 div 一个唯一的 ID 并使用 .addEventListener,我就可以这样做,但问题是我必须为每个 div 编写一个点击事件。当我尝试为每个 div 提供相同的 ID 并使用 .addEventListener 时,单击事件仅发生在第一个 div 上。

在过去的一两个小时里,我一直在搜索 Stackoverflow、Google、论坛和其他网站,并根据我发现的内容修改我的代码,但到目前为止我找不到任何有用的东西。

这是我的代码,但我只包含了前两个 div 的 HTML/CSS,因为其余的 div 就像第二个 div 并且不响应点击:

const dude = document.getElementById("dude");

dude.addEventListener("click", function(){
    dude.style.backgroundColor = "black";
});
dude.addEventListener("mouseleave", function(){
    dude.style.backgroundColor = "limegreen";
})
.container {
  display: grid;
  margin: 7rem;
  position: relative;
  grid-template-columns: auto auto auto;
  align-items: center;
  justify-content: center;
  column-gap: 2.5rem;
  row-gap: 2.5rem;
}

.box {
  background: limegreen;
  width: 10rem;
  height: 10rem;
  position: relative;
}

.box2 {
  background: limegreen;
  width: 10rem;
  aspect-ratio: 1/1;
  position: relative;
}
<div class="container">
        <div class="box" id="dude"></div>
        <div class="box2" id="dude"></div>
    </div>

非常感谢您的帮助!

标签: javascripthtmlcss

解决方案


在 HTML 中,两个或多个元素不能具有相同的 ID。在您的 HTML 中,将一个通用类添加到.container.

<div class="container">
      <div class="box gridbox"></div>
      <div class="box2 gridbox"></div>
</div>

现在使用这个 Javascript 代码:

/**
  *  Use this because we're getting the elements with 
  *  their class, not id. This method returns an array
  *  of the elements with matching class.
  */
const dudes = document.getElementsByClassName("gridbox");

/** Loop over the whole array */
for(let dude of dudes){
    /** Add click event handler */
   dude.addEventListener("click", () => {
       dude.style.backgroundColor = "black";
   });
    /** Add mouseleave event handler */
   dude.addEventListener("mouseleave", () => {
       dude.style.backgroundColor = "limegreen";
   });
}

这应该可以正常工作。


推荐阅读