You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环绑定事件时,如何为hover元素的邻近图片添加指定类?

解决hover对应元素显示邻近图片的问题

问题描述

遍历.evidence元素时,鼠标悬停任意该元素,仅第一个.evidence-img会添加display类,无法实现每个.evidence对应触发自身邻近的图片显示。

原HTML结构

<h2 class="wp-block-heading custom-font-h2 col-75 d-scroll has-large-font-size">Nato a NAPOLI<br>nel ‘92—Devoto a <span class="evidence">Reggie Miller</span> <img class="evidence-img" src="https://robertoacampora.it/wp-content/uploads/2023/05/reggie_miller_website_roberto_acampora.jpg">&amp; <span class="evidence">John Stockton</span><img class="evidence-img" src="https://robertoacampora.it/wp-content/uploads/2023/05/john-stockton_website_roberto_acampora.jpg"></h2>

问题根源

原代码中使用document.querySelector('.evidence-img')会始终返回DOM中第一个匹配的元素,导致所有hover操作都只对第一个图片生效,无法定位到当前元素的邻近图片。

解决方案一:JavaScript实现

利用nextElementSibling获取当前hover元素的下一个兄弟节点(即对应的图片),精准操作目标元素:

document.querySelectorAll('.evidence').forEach(element => {
  // 鼠标移入时添加类
  element.addEventListener('mouseover', () => {
    const targetImg = element.nextElementSibling;
    if (targetImg && targetImg.classList.contains('evidence-img')) {
      targetImg.classList.add('display');
    }
  });

  // 鼠标移出时移除类
  element.addEventListener('mouseleave', () => {
    const targetImg = element.nextElementSibling;
    if (targetImg && targetImg.classList.contains('evidence-img')) {
      targetImg.classList.remove('display');
    }
  });
});

解决方案二:纯CSS实现(更简洁)

如果仅需要通过hover控制显示/隐藏,用CSS相邻兄弟选择器即可,无需JavaScript:

/* 默认隐藏图片 */
.evidence-img {
  display: none;
}

/* hover .evidence时,显示其相邻的.evidence-img */
.evidence:hover + .evidence-img {
  display: block; /* 替换为你需要的显示样式,比如inline-block */
}

内容的提问来源于stack exchange,提问作者maurodf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:37:34