求助:将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); });
关键说明
- 用
this.querySelector('.project__caption')替代jQuery的$(this).find(),获取当前元素下的标题节点 - 用
textContent.trim()处理文本,避免空格、换行符导致的匹配失败 - 用
document.querySelectorAll+forEach遍历替代jQuery的:contains+filter,实现精确文本匹配 - 用原生
classListAPI替代jQuery的addClass/removeClass操作类名 - 最后需确保给所有需要触发hover的图片元素绑定事件,替换示例中的
.project-image-container为你实际的选择器
内容的提问来源于stack exchange,提问作者ByGio1
相关产品推荐
相关产品推荐

