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

自定义网页光标无法跟随鼠标移动问题求助

自定义光标无法跟随鼠标移动的问题修复

问题根源

  • 事件监听选错了:你用的mouseover事件只会在鼠标第一次进入页面元素时触发一次,没法持续跟踪鼠标的移动轨迹。
  • 初始位置不匹配:JS里currentX和currentY初始值设成了0,但CSS里光标默认是top:300px; left:300px,导致一开始光标位置和跟踪逻辑对不上。

修复后的完整代码

JavaScript

const cursorTag = document.querySelector("div.cursor");
const cursor = cursorTag.querySelector("div");

// 初始位置设为页面中心,避免光标一开始跳动
let currentX = window.innerWidth / 2;
let currentY = window.innerHeight / 2;
let aimX = currentX;
let aimY = currentY;
const speed = 0.3;

const animate = function () {
    currentX += (aimX - currentX) * speed;
    currentY += (aimY - currentY) * speed;

    cursor.style.left = currentX + "px";
    cursor.style.top = currentY + "px";

    requestAnimationFrame(animate);
};

animate();

// 换成mousemove事件,实时更新鼠标位置
document.addEventListener("mousemove", function (event) {
    aimX = event.pageX;
    aimY = event.pageY;
});

CSS

div.cursor div {
    z-index: 9999999;
    position: fixed;
    /* 去掉固定的top/left,让JS全权控制位置 */
    width: 45px;
    height: 45px;
    border: 1px solid #fff; /* 如果没定义--white变量,直接用#fff确保显示 */
    border-radius: 50%;
    pointer-events: none;
    transform: translate(-50%, -50%);
}

HTML

<div class="cursor">
    <div></div>
</div>

关键修复点说明

  1. 换对事件监听:把mouseover改成mousemove,这样鼠标每动一下都会更新目标位置aimX和aimY。
  2. 统一初始位置:初始时把光标位置设为页面中心,同时删掉CSS里固定的top和left,让JS完全控制光标位置,避免初始跳动。
  3. 细节优化:把speed改成const常量防止误改;如果你的项目里没定义--whiteCSS变量,直接换成#fff保证边框显示正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:51:35