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

如何实现Div随鼠标光标平滑移动?解决轮播鼠标效果卡顿问题

优化自定义光标跟随的卡顿问题

你的代码出现卡顿主要有几个核心问题:全局监听mousemove导致事件触发过于频繁、目标判断逻辑不准确,以及没有利用浏览器的动画优化机制。以下是具体的优化方案:

优化要点

  • 把mousemove事件绑定到目标容器.container上,而非全局document,减少不必要的事件触发
  • 使用requestAnimationFrame确保样式修改在浏览器重绘周期内执行,避免布局抖动
  • 修复事件对象混用的错误(原代码同时用了e和event)
  • 通过will-change提示浏览器提前优化元素的动画属性,开启硬件加速

修改后的完整代码

<style>
.img {
    width: 100px;
    height: 100px;
    object-fit: cover;
    position: fixed;
    top: 0;
    left: 0;
    /* 提示浏览器优化transform属性,开启硬件加速 */
    will-change: transform;
    /* 初始隐藏,避免未进入容器时显示 */
    opacity: 0;
    pointer-events: none; /* 避免遮挡容器的鼠标事件 */
}
.container {
    width: 700px;
    height: 900px;
    background-color: orangered;
    overflow: hidden;
    cursor: none;
}
</style>

<div class="container">
    <img
        class="img"
        src="https://images.unsplash.com/photo-1472457897821-70d3819a0e24?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2669&q=80"
    />
</div>

<script>
const container = document.querySelector(".container");
const img = container.querySelector(".img");

// 绑定事件到容器,只在容器范围内触发
container.addEventListener("mousemove", (e) => {
    // 使用requestAnimationFrame确保动画平滑
    requestAnimationFrame(() => {
        // 调整位置,让光标中心跟随鼠标(可选,根据需求调整)
        const x = e.clientX - img.offsetWidth / 2;
        const y = e.clientY - img.offsetHeight / 2;
        img.style.transform = `translate3d(${x}px, ${y}px, 0)`;
        img.style.opacity = 1;
    });
});

// 鼠标离开容器时隐藏自定义光标
container.addEventListener("mouseleave", () => {
    img.style.opacity = 0;
});
</script>

额外优化说明

  1. 事件绑定范围缩小:全局mousemove会在整个页面鼠标移动时都触发,绑定到.container后只有鼠标在容器内才会响应,大幅减少事件处理次数。
  2. requestAnimationFrame:浏览器会在每次重绘前执行这个回调,确保样式修改和页面渲染同步,避免频繁修改样式导致的卡顿。
  3. 光标位置调整:添加了偏移量让图片中心对齐鼠标,更符合常规光标体验(可根据需求移除)。
  4. 鼠标离开隐藏:补充了mouseleave事件处理,避免鼠标离开容器后自定义光标仍然显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:25:21