自定义光标滚动页面时无法跟随鼠标,仅鼠标移动后才追位
自定义光标滚动位置异常的解决方案
问题根源:你的自定义光标使用position: absolute定位,搭配pageX/pageY(相对于文档的坐标),当页面滚动时,鼠标在视口的位置未发生变化,mousemove事件不会触发,光标就停留在原来的文档位置;而absolute定位不会随视口滚动同步更新位置。
修复步骤:
- 将光标定位方式改为
fixed(相对于视口定位,滚动时保持相对视口的位置) - 使用
clientX/clientY(相对于视口的坐标)替代pageX/pageY,确保坐标匹配定位规则
修改后的完整代码:
HTML
<div class="cursor"></div> <div class="section"></div>
CSS
.section{ height:200vh; } .cursor{ display:none; width: 20px; height: 20px; border: 2px solid #f2f2f2; outline: 2px solid #000; border-radius: 50%; position: fixed; /* 改为fixed */ transition: background 0.3s ease, transform 0.3s ease; /* 明确过渡属性,去掉冗余的all */ transform-origin: center center; z-index: 20000; pointer-events: none; }
JavaScript
let mouseCursor = document.querySelector(".cursor"); window.addEventListener('DOMContentLoaded', cursor); window.addEventListener('mousemove', cursor); document.addEventListener('mouseenter', () => mouseCursor.style.display = 'block'); document.addEventListener('mouseleave', () => mouseCursor.style.display = 'none'); // 移动端移除光标逻辑保留 if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent)) { document.querySelector('.cursor').remove(); // 避免依赖jQuery,改用原生方法 } else { mouseCursor.style.display = 'block'; } function cursor(e){ // 用clientX/clientY替代pageX/pageY mouseCursor.style.top = `calc(${e.clientY}px - 1rem)`; mouseCursor.style.left = `calc(${e.clientX}px - 1rem)`; }
额外优化:
- 移除了对jQuery的依赖,改用原生DOM方法,减少不必要的库依赖
- 优化了过渡属性的写法,避免
all带来的潜在性能问题
内容的提问来源于stack exchange,提问作者gjjr
相关产品推荐
相关产品推荐

