【发布时间】:2018-10-17 20:41:22
【问题描述】:
我有一个部分,里面有 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>
【问题讨论】:
-
“我想要一个具有初始状态的图像,在其他图像之上”为什么不能用 css 完成?
-
请解释一下。可以这样做,但是当您悬停其他图像时,必须从初始图像中删除该状态。
-
啊,是的,据我所知,删除你需要 java 脚本。
标签: javascript html css hover