onMouseEnter事件失效:滚动时光标移入Div未触发事件如何修复?
解决滚动页面时元素移至鼠标下方不触发onmouseenter的问题
问题原因
onmouseenter 事件的触发逻辑是鼠标光标从元素外部主动移动到元素内部,当你滚动页面让元素“挪”到鼠标光标下方时,光标本身没有发生移动,自然不会触发这个事件。
修复方案
我们可以通过监听页面滚动事件,结合鼠标位置的记录,主动判断鼠标是否落在目标元素范围内,从而触发对应的逻辑。同时加入状态判断避免重复执行。
代码实现:
const targetDiv = document.querySelector('div'); // 标记元素是否处于hover状态 let isDivHovered = false; // 封装hover时要执行的逻辑 function triggerDivHover() { if (!isDivHovered) { console.log('hereInDivBody'); isDivHovered = true; } } // 辅助函数:判断鼠标位置是否在元素范围内 function checkMouseInElement(element, mouseX, mouseY) { const rect = element.getBoundingClientRect(); return mouseX >= rect.left && mouseX <= rect.right && mouseY >= rect.top && mouseY <= rect.bottom; } // 监听鼠标移动,记录位置同时处理正常hover window.addEventListener('mousemove', (e) => { // 把鼠标位置挂载到window上方便滚动时获取 window.currentMouseX = e.clientX; window.currentMouseY = e.clientY; if (checkMouseInElement(targetDiv, e.clientX, e.clientY)) { triggerDivHover(); } else { isDivHovered = false; } }); // 监听页面滚动,检查鼠标是否落在元素上 window.addEventListener('scroll', () => { // 确保已经记录过鼠标位置 if (typeof window.currentMouseX === 'number' && typeof window.currentMouseY === 'number') { if (checkMouseInElement(targetDiv, window.currentMouseX, window.currentMouseY)) { triggerDivHover(); } else { isDivHovered = false; } } }); // 保留原本的onmouseenter作为冗余处理 targetDiv.onmouseenter = triggerDivHover;
方案说明
- 用
mousemove事件实时记录鼠标的当前坐标,存在window对象上方便滚动时调用; - 滚动时通过
getBoundingClientRect()获取元素的实时位置,对比鼠标坐标判断是否重叠; - 用
isDivHovered状态变量避免每次滚动或鼠标移动都重复执行hover逻辑; - 保留原本的
onmouseenter事件作为补充,确保常规场景下的触发逻辑正常。
内容的提问来源于stack exchange,提问作者Naveed Ali Rehmani
相关产品推荐
相关产品推荐

