Javascript 如何分离突出显示的对象
在我的网站上,我有5个类别。在每个类别中,我都有一个带有标题的图像和一个描述文本。当鼠标悬停在图像上时,图像和文本会同时高亮显示(通过添加一个类:“highligthCategory”) 我的问题是,每次我将鼠标悬停在5幅图像上,所有5幅描述都会突出显示。如何将突出显示限制为仅与一个图像相关的特定描述 我假设出现问题的原因是第二个循环在第一个循环内,但由于我也有事件侦听器,我不知道如何将它们分开,使两个循环分别工作Javascript 如何分离突出显示的对象,javascript,Javascript,在我的网站上,我有5个类别。在每个类别中,我都有一个带有标题的图像和一个描述文本。当鼠标悬停在图像上时,图像和文本会同时高亮显示(通过添加一个类:“highligthCategory”) 我的问题是,每次我将鼠标悬停在5幅图像上,所有5幅描述都会突出显示。如何将突出显示限制为仅与一个图像相关的特定描述 我假设出现问题的原因是第二个循环在第一个循环内,但由于我也有事件侦听器,我不知道如何将它们分开,使两个循环分别工作 const category = document.querySelectorA
const category = document.querySelectorAll(".category");
const categoryText = document.querySelectorAll(".category-text");
const categoryArray = Array.prototype.slice.call(category);
const categoryTextArray = Array.prototype.slice.call(categoryText);
categoryArray.map(x => {
x.addEventListener ("mouseover", function(e) {
categoryTextArray.map(y =>
y.classList.add("highligthCategory"));
}, false);
x.addEventListener ("mouseout", function(e) {
categoryTextArray.map(y =>
y.classList.remove("highligthCategory"));
}, false);
});
HTML
<section id="service-1">
<div class="row">
<figure>
<img class="category" src="img/1.svg" alt="" data- type="feature">
</figure>
<h3>Service 1</h3>
<p class="category-text">Example of the text.</p>
</div>
</section>
const category=document.queryselectoral(“.category”);
const categoryText=document.queryselectoral(“.category text”);
const categoryArray=Array.prototype.slice.call(category);
const categoryTextArray=Array.prototype.slice.call(categoryText);
categoryArray.map(x=>{
x、 addEventListener(“鼠标悬停”,函数(e){
categoryTextArray.map(y=>
y、 添加(“高亮度类别”);
},假);
x、 addEventListener(“鼠标出”,函数(e){
categoryTextArray.map(y=>
y、 类列表。删除(“highligthCategory”);
},假);
});
HTML
服务1
文本示例
问题在于,在事件侦听器中,您正在修改所有.category文本
元素,而不仅仅是与触发事件的元素相关的元素。您可以执行以下操作来修复该问题:
const categories=document.queryselectoral(“.category”);
类别。forEach(类别=>{
const description=category.closest('.row').querySelector('.category text');
category.addEventListener(“鼠标悬停”,()=>{
description.classList.add(“highligthCategory”);
},假);
category.addEventListener(“mouseout”,()=>{
description.classList.remove(“highligthCategory”);
},假);
});代码>
.highligthCategory{
颜色:红色;
}
服务1
文本示例
服务1
文本示例
您可以添加一些HTML来说明.category
和.category text
元素之间的关系吗?我已经添加了上面一节的代码。总共有5个部分的结构完全相同。谢谢你-你太棒了-它完美地解决了我的问题!