如何使用 addEventListener( "click" ) 更改相同 id 的多个 div 的颜色?



你好,

我有一个由9个正方形div组成的CSS网格,我想为所有这些div添加一个点击事件,这样它们的颜色就会从灰绿色变为黑色,然后在鼠标离开时变回灰绿色。如果我给每个div一个唯一的ID并使用.addEventListener,我就能做到这一点,但问题是我必须为每个div编写一个点击事件。当我试图给每个div相同的ID并用.addEvent监听器时,点击事件只发生在第一个div上。

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

这是我的代码,但我只包含了前两个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>

非常感谢你的帮助!

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

这应该很好用。

最新更新