我有一个包含 4 张图片的部分。我希望悬停图像获得一个类,因此它显示在其他图像之上。我不单独使用 CSS 执行此操作的原因是我想要一个具有该初始状态的图像,位于其他图像之上。
我很接近 mouseover
但我希望该类保留在最后悬停的图像中,而不是在鼠标离开时消失,就像单击事件一样。
//Getting all the images in an Array:
const imagesArr = Array.from( document.querySelectorAll(".portfolio-single-image") );
//The container where the images are:
const mainGrid = document.querySelector("main");
//The event listener where the class is assigned and removed from the other elements:
mainGrid.addEventListener("mouseover", function(e){
imagesArr.map((image)=> image.classList.remove("active-image") );
e.target.classList.add("active-image");
});
HTML:
<main>
<img class="portfolio-single-image image1 active-image" src="X" alt="">
<img class="portfolio-single-image image2" src="X" alt="">
<img class="portfolio-single-image image3" src="X" alt="">
<img class="portfolio-single-image image4" src="X" alt="">
</main>
最佳答案
检查事件目标是否为图像。添加/删除类仅在鼠标位于类 portfolio-single-image
的元素上时才有效。
//Getting all the images in an Array:
const imagesArr = Array.from( document.querySelectorAll(".portfolio-single-image") );
//The container where the images are:
const mainGrid = document.querySelector("main");
//The event listener where the class is assigned and removed from the other elements:
mainGrid.addEventListener("mouseover", function(e){
if(e.target.classList.contains('portfolio-single-image')){
imagesArr.map((image)=> image.classList.remove("active-image") );
e.target.classList.add("active-image");
}
});
.active-image {
border:1px solid red;
display:block;
}
<main>
<img class="portfolio-single-image image1 active-image" src="X" alt="">
<img class="portfolio-single-image image2" src="https://via.placeholder.com/350x150" alt="">
<img class="portfolio-single-image image3" src="https://via.placeholder.com/350x150" alt="">
<img class="portfolio-single-image image4" src="https://via.placeholder.com/350x150" alt="">
</main>
关于javascript - 当鼠标离开时维护由悬停事件分配的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52854685/