鼠标跟随特效需监听mousemove/touchmove事件记录坐标,用requestAnimationFrame平滑更新transform位移,禁用pointer-events并设z-index防遮挡。

HTML5 页面中实现鼠标跟随特效的核心思路
鼠标跟随特效本质是监听 mousemove 事件,动态更新一个 DOM 元素(比如 )的 left 和 top 值。HTML5 本身不提供“内置跟随”功能,必须靠 JavaScript 控制,CSS 负责视觉表现和过渡动画。
用 requestAnimationFrame 替代直接设置 style.left/top
直接在 mousemove 里频繁修改样式会导致卡顿,尤其在高刷新率屏幕或低端设备上。正确做法是把位置更新交给 requestAnimationFrame 批量处理,避免强制同步布局(layout thrashing)。
- 监听
mousemove只记录最新坐标:let x = e.clientX, y = e.clientY - 用
requestAnimationFrame驱动一个独立的更新函数,每次只改一次样式 - 确保目标元素已设
position: fixed或absolute,且pointer-events: none,否则会干扰原页面交互
let cursor = document.querySelector('.cursor');
let x = 0, y = 0;
let targetX = 0, targetY = 0;
document.addEventListener('mousemove', e => {
targetX = e.clientX;
targetY = e.clientY;
});
function animate() {
x += (targetX - x) 0.1;
y += (targetY - y) 0.1;
cursor.style.left = ${x}px;
cursor.style.top = ${y}px;
requestAnimationFrame(animate);
}
animate();
CSS 中必须加 transform: translate() 提升性能
用 left/top 移动元素会触发重排(reflow),而 transform: translate() 仅触发重绘(repaint),GPU 加速更平滑。即使 JS 里用的是 left/top,也应改用 transform。
- 把 JS 中的
cursor.style.left = ...换成cursor.style.transform = `translate(${x}px, ${y}px)` - CSS 中给
.cursor设will-change: transform(可选,对复杂动画有帮助) - 避免同时设置
left和transform,否则行为不可预测
兼容移动端需额外处理触摸事件
纯 mousemove 在手机上完全无效。如果模板要支持触屏设备,必须监听 touchmove 并取 touches[0] 的坐标。注意:移动端一次触摸可能触发多次 touchmove,但不需要额外节流——requestAnimationFrame 已天然控制帧率。
立即学习“前端免费学习笔记(深入)”;
- 同时绑定
mousemove和touchmove,共用同一套坐标更新逻辑 -
touchmove事件对象没有clientX/Y,要用e.touches[0].clientX - 在
touchstart时显示光标,在touchend后隐藏(可选,提升体验)
真实项目中最容易被忽略的是:未禁用光标的 pointer-events,导致点击按钮时实际点中了跟随层;还有就是忘了在 CSS 中设 z-index,让自定义光标被其他元素遮挡。这两个问题调试起来非常隐蔽。










