贝利信息

如何实现鼠标移动时元素实时跟随无延迟效果

日期:2025-12-29 00:00 / 作者:花韻仙語

本文介绍一种通过隐藏原生光标并使用 css `translate` 驱动父容器位移的高性能方案,彻底解决传统 `mousemove` + `offsetleft/top` 更新导致的视觉延迟问题,适用于点击躲避类交互游戏。

在开发鼠标跟随类交互(如“躲猫猫”式点击游戏)时,直接监听 mousemove 并逐个更新 DOM 元素的 left/top 样式会产生明显延迟——这是因为 offsetLeft/offsetTop 触发强制同步布局(Layout Thrashing),且每次重排重绘开销大,尤其在多元素场景下愈发卡顿。

根本优化思路:避免逐元素操作,改用单次 CSS 变换驱动整体位移

核心技巧是:

以下是精简可复用的实现代码:


* { margin: 0; box-sizing: border-box; cursor: none; }
body { height: 100dvh; overflow: hidden; }
#pointers {
  position: absolute;
  width: 100%; height: 100%;
  background: url("https://i.sstatic.net/Zt6te.png") calc(50% + 2px) calc(50% + 14px) no-repeat;
  pointer-events: none; /* 关键:允许底层按钮正常接收点击 */
}
.pointer {
  position: absolute;
  width: 25px; height: 32px;
  background: url("https://i.sstatic.net/Zt6te.png");
}
#btn {
  position: absolute;
  border: none; border-radius: 5px;
  background: #000; color: #fff;
  padding: 0.5rem 0.7rem; font-size: 12px;
  font-family: 'Roboto', sans-serif;
  translate: -50% -50%; /* 居中锚点 */
}
const el = sel => document.querySelector(sel);
const rand = (min, max) => Math.random() * (max - min) + min;
const elBody = el('body');
const elPointers = el('#pointers');
const elBtn = el('#btn');

// 初始化按钮位置
const moveBtn = () => {
  elBtn.style.left = `${rand(5, 95)}%`;
  elBtn.style.top = `${rand(5, 95)}%`;
};

// 动态生成假光标(随机数量+随机位置)
const createPointers = () => {
  const count = Math.floor(rand(3, 10));
  elPointers.innerHTML = '';
  for (let i = 0; i < count; i++) {
    const ptr = document.createElement('div');
    ptr.className = 'pointer';
    ptr.style.left = `${rand(0, 100)}%`;
    ptr.style.top = `${rand(0, 100)}%`;
    elPointers.appendChild(ptr);
  }
};

// 关键:仅更新容器 translate,零布局计算
const movePointers = (e) => {
  const xCenter = (e.clientX / elBody.offsetWidth) - 0.5;
  const yCenter = (e.clientY / elBody.offsetHeight) - 0.5;
  elPointers.style.translate = `${xCenter * 100}% ${yCenter * 100}%`;
};

// 绑定事件
elBtn.addEventListener('click', () => {
  createPointers();
  moveBtn();
  elBody.style.background = `hsl(${Math.floor(rand(0, 360))}, 80%, 50%)`;
});
elBody.addEventListener('pointermove', movePointers);

// 启动
moveBtn();
createPointers();

优势总结

⚠️ 注意事项