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

React自定义光标滚动超出视口后无法跟随鼠标的问题求助

解决React自定义光标滚动后位置偏移问题

问题描述

在React项目中实现自定义光标后,当页面滚动超过视口高度时,光标无法正确跟随鼠标位置。

问题原因

  1. 原代码使用clientY作为光标垂直坐标,clientY是相对于浏览器视口的坐标,不包含页面滚动的偏移量。
  2. 光标采用position: absolute定位,而body被设置为固定的height: 100vh,当页面内容超出视口高度时,body不会跟随页面滚动,导致光标基于视口的坐标与实际鼠标位置出现偏差。

解决方案

方案一:改用position: fixed定位光标(推荐)

将光标元素改为固定定位,使其始终相对于浏览器视口定位,配合clientX/clientY即可实现滚动时的正确跟随。

修改Cursor.scss:

@import "/src/Utilities/Varibles.scss";

*{
   cursor: none;
 }
 
 .cursor {
   position: fixed; /* 替换absolute为fixed */
   width: 40px;
   height: 40px;
   background: $green;
   border-radius: 50%;
   top: var(--y, 0);
   left: var(--x, 0);
   transform: translate(-50%, -100%);
   z-index: 2;
   mix-blend-mode: difference;
   pointer-events: none;
 }

App.js中的鼠标移动监听无需修改,保留原逻辑即可:

document.onmousemove = function(e) {
  document.body.style.setProperty('--x',(e.clientX)+'px');
  document.body.style.setProperty('--y',(e.clientY)+'px');
}

方案二:调整body高度并使用文档坐标

如果需要保留position: absolute,可以修改body的高度为自适应文档内容,同时使用pageX/pageY(相对于文档顶部的坐标)来定位光标。

  1. 修改index.scss中的body样式:
body {
  background-color: $blue;
  width: 100vw;
  min-height: 100vh; /* 替换height为min-height */
  overflow-x: hidden;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
  display: flex;
  flex-direction: column;
  margin: 0 auto;

  &::-webkit-scrollbar {
    display: none;
  }
}
  1. 修改App.js中的鼠标监听逻辑:
document.onmousemove = function(e) {
  document.body.style.setProperty('--x',(e.pageX)+'px');
  document.body.style.setProperty('--y',(e.pageY)+'px');
}

说明

  • 方案一的fixed定位更简洁,无需调整body样式,光标始终跟随视口内的鼠标位置,适合大多数场景。
  • 方案二适合需要基于文档流定位光标的特殊场景,确保光标坐标与文档滚动状态同步。

内容的提问来源于stack exchange,提问作者Marc López Soler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:44:58