javascript - 当鼠标离开时维护由悬停事件分配的类

标签 javascript html css hover

我有一个包含 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/

相关文章:

javascript - 在 C# 文件中调用 javascript 函数

javascript - 在渲染函数中使用动态 Vue 组件

javascript - slider 无法显示

html - header CSS 中断

javascript - jQuery - 确保内容在淡入之前加载?

html - 在移动浏览器中使用自动填充功能将背景图像添加到输入字段 - 默认黄色背景会删除它们

javascript - 为什么我的 for 循环似乎只运行一次?

javascript - 使用 Javascript 发出 HTTP POST 身份验证基本请求

javascript - 为什么 Html 表单不显示在图像上

html - IE8-同一过滤器中的渐变和背景图像不起作用?