【问题标题】:How can I change color of more than one div of the same id using addEventListener("click")? [duplicate]如何使用 addEventListener("click") 更改多个具有相同 id 的 div 的颜色? [复制]
【发布时间】:2021-07-18 09:28:12
【问题描述】:

早安,

我有一个由 9 个方形 div 组成的 CSS 网格,我想为所有这些 div 添加一个单击事件,以便它们的颜色从浅绿色变为黑色,然后在鼠标离开时又变回浅绿色。如果我给每个 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>

非常感谢您的帮助!

【问题讨论】:

  • 是的,它完全有帮助!谢谢!我从错误的角度看待一切。

标签: javascript html css


【解决方案1】:

在 HTML 中,两个或多个元素不能具有相同的 ID。 在您的 HTML 中,将公共类添加到 .container 内的 div。

<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";
   });
}

这应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2012-12-02
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多