我正在尝试对网格应用悬停效果,因此当我的鼠标经过容器时,某个网格正方形将变为黑色。但是,当我将鼠标悬停在网格上时,整个网格变成黑色。我已经意识到,当有多个具有相同类名的元素时,它将改变所有元素的颜色。
var hoverContainer = document.getElementById('container');
hoverContainer.addEventListener('mouseover', function(e) {
var colorChange = document.getElementsByClassName('grid-item');
for(var i = 0; i < colorChange.length; i++){
colorChange[i].classList.add('hoverColor');
console.log(e);
}
});
我希望朝正确的方向前进!谢谢!
答案 0 :(得分:0)
尝试将closest
.grid-item
找到target
并更改其classList
:
var hoverContainer = document.getElementById('container');
hoverContainer.addEventListener('mouseover', function(e) {
const gridItem = e.target.closest('.grid-item');
if (gridItem) gridItem.classList.add('hoverColor');
});
.grid-item {
border: 1px solid black;
}
.hoverColor {
background-color: yellow;
}
<div id="container">
<div class="grid-item">item</div>
<div class="grid-item">item</div>
<div class="grid-item">item</div>
<div class="grid-item">item</div>
</div>
(鼠标离开hoverColor
后,您还需要删除.grid-item
)
但是,仅使用CSS,:hover
就可以轻松实现:
.grid-item {
border: 1px solid black;
}
.grid-item:hover {
background-color: yellow;
}
<div id="container">
<div class="grid-item">item</div>
<div class="grid-item">item</div>
<div class="grid-item">item</div>
<div class="grid-item">item</div>
</div>