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

无需使用图片,能否将CSS动画红色方块替换为自定义光标效果

实现方案

完全可以实现,不需要引入任何图片,只要在你原有代码基础上做少量调整即可,既可以保留原有的动画效果,也可以让自定义元素跟随鼠标移动作为光标使用。

核心改造点

  • 给页面全局添加cursor: none隐藏系统默认光标
  • 增加少量JS代码让自定义的方块元素实时跟随鼠标坐标
  • 你可以任意修改.pointer的CSS属性调整光标样式,比如改成圆形、半透明、边框效果等,所有样式都可以纯CSS实现

完整可运行代码

HTML代码

<body>
  <span class="pointer"></span>

  <script>
    const customCursor = document.querySelector('.pointer')
    document.addEventListener('mousemove', e => {
      // 调整偏移量让光标中心对准鼠标点击位置
      const offsetX = customCursor.offsetWidth / 2
      const offsetY = customCursor.offsetHeight / 2
      customCursor.style.left = `${e.clientX - offsetX}px`
      customCursor.style.top = `${e.clientY - offsetY}px`
    })
  </script>
</body>

CSS代码

/* 隐藏系统默认光标 */
body {
  cursor: none;
  margin: 0;
  min-height: 100vh;
}

.pointer {
  width: 20px; /* 可以调整成你想要的光标大小 */
  height: 20px;
  background: #ff4444; /* 可以任意改颜色 */
  border-radius: 50%; /* 加这行变成圆形光标,去掉就是原有的方块 */
  position: fixed;
  z-index: 9999; /* 保证光标在所有元素最上层 */
  pointer-events: none; /* 关键属性:让光标不干扰页面其他元素的点击事件 */
  /* 如果你不需要原有的路径动画可以删掉下面三行,这里示例改成了更适合光标的呼吸缩放动画 */
  animation-name: mouse;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@keyframes mouse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.5);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

关键说明

  • pointer-events: none是必须的属性,否则自定义的光标元素会挡住页面上其他元素的点击、hover等交互
  • 如果你想保留原有的left/bottom路径动画,直接替换@keyframes里的代码即可
  • 可以任意调整.pointer的样式,比如加边框、阴影、渐变等,全部都可以纯CSS实现,不需要任何图片资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:24:03