如何创建有限范围跟随鼠标的悬停动画效果?
实现播放按钮的鼠标跟随悬停效果
关于GSAP的使用
你提到的halo-lab网站上的这个按钮跟随效果,确实是借助GSAP实现的——GSAP的gsap.to()方法可以轻松实现带缓动的属性过渡,非常适合这类鼠标跟随的平滑动画。不过不用GSAP,原生JavaScript也能复刻核心效果。
完整实现代码
下面是整合了颜色变化+鼠标跟随的完整代码:
HTML
<a href="#" class="button-play"> <div class="button-play__bg"></div> <svg aria-hidden="true" role="img" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="100%" height="100%"> <path d="M13.9 7.35a.7.7 0 0 1 0 1.213l-8.4 4.85a.7.7 0 0 1-1.05-.606v-9.7a.7.7 0 0 1 1.05-.606l8.4 4.85Z"></path> </svg> </a>
CSS
.button-play{ background: #02021e; color: white; display: flex; width: 7rem; height: 7rem; border-radius: 50%; align-items: center; justify-content: center; position: relative; transition: color .4s; will-change: transform; transform-style: preserve-3d; margin: 70px; cursor: pointer; } .button-play__bg{ background-color: #3827c7; border-radius: 50%; width: 100%; height: 100%; transition: all .3s; position: absolute; inset: 0%; transform: scale(0); } .button-play svg{ width: 1.75rem; height: 1.75rem; position: relative; z-index: 2; } .button-play:hover .button-play__bg{ transform: scale(1) }
JavaScript(原生实现)
const playButton = document.querySelector('.button-play'); const maxOffset = 8; // 最大偏移量,控制跟随范围 playButton.addEventListener('mousemove', (e) => { // 获取按钮的位置和尺寸 const rect = playButton.getBoundingClientRect(); // 计算鼠标在按钮内的相对位置(中心为原点) const x = e.clientX - rect.left - rect.width / 2; const y = e.clientY - rect.top - rect.height / 2; // 将相对位置转换为比例,限制在[-1,1]范围内,再乘以最大偏移量 const offsetX = Math.max(-maxOffset, Math.min(maxOffset, (x / (rect.width / 2)) * maxOffset)); const offsetY = Math.max(-maxOffset, Math.min(maxOffset, (y / (rect.height / 2)) * maxOffset)); // 应用transform偏移 playButton.style.transform = `translate3d(${offsetX}px, ${offsetY}px, 0px)`; }); // 鼠标离开时重置位置 playButton.addEventListener('mouseleave', () => { playButton.style.transform = 'translate3d(0px, 0px, 0px)'; });
JavaScript(GSAP实现,更平滑)
如果你想用GSAP来实现更丝滑的缓动效果,可以这样写:
const playButton = document.querySelector('.button-play'); const maxOffset = 8; playButton.addEventListener('mousemove', (e) => { const rect = playButton.getBoundingClientRect(); const x = e.clientX - rect.left - rect.width / 2; const y = e.clientY - rect.top - rect.height / 2; const targetX = Math.max(-maxOffset, Math.min(maxOffset, (x / (rect.width / 2)) * maxOffset)); const targetY = Math.max(-maxOffset, Math.min(maxOffset, (y / (rect.height / 2)) * maxOffset)); // 用GSAP实现平滑过渡 gsap.to(playButton, { x: targetX, y: targetY, duration: 0.3, ease: 'power2.out' }); }); playButton.addEventListener('mouseleave', () => { gsap.to(playButton, { x: 0, y: 0, duration: 0.5, ease: 'elastic.out(1, 0.3)' }); });
效果说明
- 鼠标在按钮范围内移动时,按钮会跟随鼠标产生小范围偏移,超出最大限制后不再继续移动
- 鼠标离开时,按钮会平滑回归初始位置
- 保留了你已经实现的背景缩放颜色变化效果
内容的提问来源于stack exchange,提问作者user933061
相关产品推荐
相关产品推荐

