自定义悬浮光标滚动偏移及粘连异常问题排查求助
自定义悬浮光标问题排查与修复
问题描述
在#video-container容器上实现自定义悬浮光标(#play元素)时遇到两个问题:
- 向上滚动时光标无法跟随鼠标移动,停留在原位;移除GSAP加载动画后恢复正常。
- 鼠标处于
#play内时,即便#video-container已绑定mouseenter、mouseleave和mousemove事件,光标仍会粘连在鼠标上,需移出才消失。
问题原因分析
1. 滚动时光标定位错乱
GSAP的from动画会给目标元素添加内联样式(比如transform: translateY(100px)),默认动画结束后不会清除这些样式。当#video-container被添加transform属性后,其内部的fixed定位元素#play会相对于变换后的容器定位,而非视口,导致滚动时位置异常。
2. 鼠标在#play上时粘连
#play是#video-container的子元素,但fixed定位使其脱离文档流,鼠标移动到#play上时,#video-container的mousemove事件捕获会受影响;同时#play默认接收鼠标事件,会干扰父元素的mouseleave判断逻辑,导致光标无法及时隐藏。
修复方案
解决滚动定位问题
给GSAP动画添加clearProps: "all"配置,让动画结束后自动清除所有内联样式,避免transform影响子元素定位。
解决鼠标粘连问题
给#play添加pointer-events: none,使其不接收任何鼠标事件,确保鼠标在#play上时,事件仍正常作用于#video-container。
修改后的JavaScript代码
function loadingAnim() { gsap.from("#page1 h1", { y: 100, opacity: 0, delay: 0.5, duration: 0.9, stagger: 0.2, clearProps: "all" // 清除动画残留的内联样式 }); gsap.from("#page1 #video-container", { y: 100, opacity: 0, delay: 1.5, duration: 0.9, clearProps: "all" // 关键修复:清除transform属性 }); } loadingAnim(); function videoCursor() { var videocon = document.querySelector("#video-container"); var playbtn = document.querySelector("#play"); videocon.addEventListener("mouseenter", () => { gsap.to(playbtn, { scale: 1, opacity: 1, duration: 0.3 }); }); videocon.addEventListener("mouseleave", () => { gsap.to(playbtn, { scale: 0, opacity: 0, duration: 0.3 }); }); videocon.addEventListener("mousemove", (dets) => { gsap.to(playbtn, { left: dets.clientX - 60, top: dets.clientY - 60, duration: 0.1, overwrite: true // 避免动画堆积导致的跟随延迟 }); }); } videoCursor();
修改后的CSS代码
* { margin: 0; padding: 0; box-sizing: border-box; font-family: "Gilroy-Medium", sans-serif; } *::selection { color: #fff; background-color: #000; } html, body { height: 100%; width: 100%; overflow-x: hidden; } #page1 { position: relative; min-height: 100vh; width: 100vw; padding: 0 1.5vw; padding-top: 20vh; } #page1 h1 { font-size: 15.9vw; font-family: futura; text-transform: uppercase; line-height: 14vw; letter-spacing: -0.5vw; } #video-container { height: 100vh; width: 95vw; background-color: gray; margin-top: 2vw; position: relative; } #video-container video { height: 100%; width: 100%; object-fit: cover; } #video-container #play { position: fixed; padding: 3vw 2vw; background-color: #000; color: #fff; text-transform: uppercase; font-family: futura; font-size: 1.5vw; border-radius: 50%; opacity: 0; scale: 0; pointer-events: none; /* 关键:让元素不拦截鼠标事件 */ }
内容的提问来源于stack exchange,提问作者saribcantcode
相关产品推荐
相关产品推荐

