如何让自定义跟随光标悬停菜单文本时匹配其尺寸与固定位置
问题排查
你的代码存在4个核心问题导致效果不达标:
- 悬停回调中只配置了
top属性,未配置left属性,光标水平位置错误 - 全局
mousemove事件没有做状态拦截,悬停时仍然会持续改写光标位置,导致固定位置失效 - 页面初始化时就提前读取了文本元素的尺寸和位置,后续如果页面缩放、布局变动,缓存的数值会过期
- 文本元素的
offsetLeft/offsetTop是相对于其父级定位元素的偏移,和直接挂在body下的光标元素定位基准不一致,直接赋值会出现位置偏差
修复代码
JS 逻辑修改
let cursor = document.querySelector('.cursorFollower'); let button = document.querySelector('.superText'); // 新增悬停状态标记,用于控制光标跟随逻辑是否生效 let isHover = false; document.addEventListener('mousemove',(e)=>{ // 悬停状态下跳过光标跟随逻辑 if(isHover) return cursor.style.left = e.pageX - 10 + 'px'; cursor.style.top = e.pageY - 10 + 'px'; }); button.onmouseover = function(){ isHover = true button.style.color = "#84C4B5"; cursor.style.transform = 'rotate(0deg)'; // 悬停时实时读取元素的尺寸、坐标,自动适配布局变动 const btnRect = button.getBoundingClientRect() cursor.style.width = `${btnRect.width}px`; cursor.style.height = `${btnRect.height}px`; // 兼容页面滚动场景,计算绝对定位的准确坐标 cursor.style.top = `${btnRect.top + window.scrollY}px`; cursor.style.left = `${btnRect.left + window.scrollX}px`; }; button.onmouseout = function(){ isHover = false button.style.color = "white"; cursor.style.transform = 'rotate(45deg)'; cursor.style.width = '20px'; cursor.style.height = '20px'; };
其他说明
你原有HTML和CSS代码无需修改,即可实现要求效果。如果需要适配多个菜单文本,把querySelector('.superText')改为querySelectorAll遍历绑定事件即可,逻辑可以直接复用。
内容的提问来源于stack exchange,提问作者Eugenio
相关产品推荐
相关产品推荐

