自定义网页光标无法跟随鼠标移动问题求助
自定义光标无法跟随鼠标移动的问题修复
问题根源
- 事件监听选错了:你用的
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>
关键修复点说明
- 换对事件监听:把
mouseover改成mousemove,这样鼠标每动一下都会更新目标位置aimX和aimY。 - 统一初始位置:初始时把光标位置设为页面中心,同时删掉CSS里固定的
top和left,让JS完全控制光标位置,避免初始跳动。 - 细节优化:把
speed改成const常量防止误改;如果你的项目里没定义--whiteCSS变量,直接换成#fff保证边框显示正常。
内容的提问来源于stack exchange,提问作者Mahmoud Kattan
相关产品推荐
相关产品推荐

