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

求助:将jQuery鼠标悬停/移出函数转为原生JS,实现图片标题交互

原生JavaScript实现鼠标悬停显示对应克隆标题

先修正HTML结构问题

HTML中id属性必须唯一,你当前8个元素都使用id="project__caption"不符合规范,建议统一改为class="project__caption",后续代码均基于class处理。

克隆代码修正(对应原代码)

cursorText: function () {
  if (!isMobile() || !isTouchDevice()) {
    // 把#project__caption改为.project__caption
    const projectCap = document.querySelectorAll('.project__caption');
    const cursorText = document.getElementById('cursor-outer');

    for (let i = 0; i < projectCap.length; i++) {
      const element = projectCap[i];
      const cloned = cursorText.appendChild(element.cloneNode(true));
      cloned.classList.add('is-inactive');
    }    
  }
},

替换jQuery的hover事件为原生JS

// 鼠标悬停时显示对应克隆标题
function mouseOver() {
  // 获取当前元素关联的标题文本(去除首尾空格避免匹配误差)
  const hoveredText = this.querySelector('.project__caption').textContent.trim();
  // 获取#cursor-outer下所有克隆的标题元素
  const clonedCaptions = document.querySelectorAll('#cursor-outer .project__caption');

  clonedCaptions.forEach(caption => {
    // 精确匹配文本内容
    if (caption.textContent.trim() === hoveredText) {
      caption.classList.remove('is-inactive');
      caption.classList.add('is-active');
    }
  });
}

// 鼠标移出时隐藏对应克隆标题
function mouseOut() {
  const hoveredText = this.querySelector('.project__caption').textContent.trim();
  const clonedCaptions = document.querySelectorAll('#cursor-outer .project__caption');

  clonedCaptions.forEach(caption => {
    if (caption.textContent.trim() === hoveredText) {
      caption.classList.remove('is-active');
      caption.classList.add('is-inactive');
    }
  });
}

// 给所有图片/图片容器绑定事件(替换成你实际的图片容器选择器)
const projectItems = document.querySelectorAll('.project-image-container'); // 示例选择器,需替换
projectItems.forEach(item => {
  item.addEventListener('mouseover', mouseOver);
  item.addEventListener('mouseout', mouseOut);
});

关键说明

  1. 用this.querySelector('.project__caption')替代jQuery的$(this).find(),获取当前元素下的标题节点
  2. 用textContent.trim()处理文本,避免空格、换行符导致的匹配失败
  3. 用document.querySelectorAll+forEach遍历替代jQuery的:contains+filter,实现精确文本匹配
  4. 用原生classListAPI替代jQuery的addClass/removeClass操作类名
  5. 最后需确保给所有需要触发hover的图片元素绑定事件,替换示例中的.project-image-container为你实际的选择器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:10:32