【发布时间】: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