JS自定义光标交互异常:鼠标停移后mousemove失效,链接hover与点击功能异常
自定义光标交互异常修复
问题根因
- 自定义光标的DOM块未配置鼠标穿透规则:该元素
z-index: 1000处于页面最高层级,默认会拦截所有途经的鼠标事件,点击、hover的判定对象实际是光标本身,而非下方的链接元素,直接造成链接无法点击、鼠标静止时光标遮挡链接触发hover失效。 - 代码存在类名拼写错误:原扩圈类名写为
curson-expand,拼写偏差导致点击动效无法正常挂载。 - 定位逻辑错位:原代码用
pageX/pageY搭配position: absolute实现定位,页面滚动时会出现光标与真实鼠标位置偏移,进一步加剧交互异常。
修复步骤
- 给
.cursor添加pointer-events: none属性,让光标仅承担视觉展示作用,不参与任何鼠标交互判定,所有点击、hover事件会直接穿透到下方的真实页面元素,这是解决当前问题的核心操作。 - 将光标定位改为
position: fixed,搭配clientX/clientY计算位置,避免页面滚动时出现光标漂移。 - 修正拼写错误的类名,统一替换为
cursor-expand,确保点击扩圈动效正常生效。 - 如需完全替换系统默认光标,放开
cursor: none的全局注释即可。
修复后完整代码
样式代码
*, body { cursor: none; } .cursor { width: 20px; height: 20px; border: 1px solid #000; border-radius: 50%; position: fixed; pointer-events: none; z-index: 1000; transition: all ease 0.1s; } .cursor-expand { width: 30px; height: 30px; border: 3px solid #d6a309; } h2 { font-family: Arial Black, Arial Bold, sans-serif; } h2 a { text-decoration: none; color: inherit; } h2 a:hover { color: #d6a309; text-decoration: underline; }
交互逻辑代码
const cursor = document.querySelector(".cursor"); document.addEventListener("mousemove", e => { cursor.setAttribute("style", `top: ${e.clientY - 10}px; left: ${e.clientX - 10}px;`); }); document.addEventListener("click", (e) => { cursor.classList.add("cursor-expand"); cursor.setAttribute("style", `top: ${e.clientY - 15}px; left: ${e.clientX - 15}px;`); setTimeout(() => { cursor.classList.remove("cursor-expand"); cursor.setAttribute("style", `top: ${e.clientY - 10}px; left: ${e.clientX - 10}px;`); }, 500) });
误区提示
此前尝试替换mouseover、mouseenter事件及对应监听器未解决问题,本质是未触达核心拦截点:当顶层光标块默认拦截鼠标事件时,所有绑定在下层元素的事件都无法被触发,单纯更换事件类型完全无法穿透实体DOM块的拦截。
内容的提问来源于stack exchange,提问作者Nirzar
相关产品推荐
相关产品推荐

