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

自定义光标图片触发mouseleave事件后未消失的问题排查

问题分析与解决方案

问题原因

自定义光标图片默认会捕获鼠标事件(pointer-events: auto),且它是.box的子元素。当鼠标移动到光标图片上时,鼠标实际仍处于.box的子元素范围内,不会触发.box的mouseleave事件;当你试图将鼠标移出.box时,光标图片会跟随鼠标移动,导致鼠标始终停留在.box的子元素上,永远无法触发mouseleave,因此光标无法隐藏。

修复代码

只需给自定义光标添加pointer-events: none样式,让鼠标事件穿透光标图片,直接作用于下方的.box:

const box = document.querySelector(".box");

const customCursor = document.createElement("img");

customCursor.style.width = "175px";
customCursor.style.height = "175px";
customCursor.style.position = "absolute";
customCursor.src = "https://picsum.photos/175";
customCursor.style.display = "none";
// 禁用光标图片的鼠标事件,让事件穿透到.box
customCursor.style.pointerEvents = "none";

box.appendChild(customCursor);

// 可选优化:给.box添加相对定位,让光标相对于.box定位,避免布局偏移
box.style.position = "relative";

box.addEventListener("mousemove", (e) => {
  customCursor.style.display = "block";
  customCursor.style.left = `${e.pageX - customCursor.width / 2}px`;
  customCursor.style.top = `${e.pageY - customCursor.height / 2}px`;
});

box.addEventListener("mouseleave", () => {
  customCursor.style.display = "none";
});

额外说明

  • pointer-events: none会让元素不再接收任何鼠标事件,鼠标操作会直接作用于它下方的元素,这样.box的mouseleave就能在鼠标真正离开区域时触发。
  • 给.box添加position: relative是可选优化,确保自定义光标的绝对定位相对于.box,避免页面滚动或布局变化时光标位置偏移。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:57:16