实现思路:
html:
Hover me
css:
/*按钮基本样式*/.mouse-cursor-gradient-tracking { position: relative; background: #7983ff; padding: 0.5rem 1rem; font-size: 1.2rem; border: none; color: white; cursor: pointer; outline: none; overflow: hidden;}.mouse-cursor-gradient-tracking span { position: relative;}/*按钮渐变背景,这里使用伪类实现,并且使用transform动画*/.mouse-cursor-gradient-tracking:before { –size: 0; /*渐变背景尺寸*/ content: ”; position: absolute; left: var(–x); top: var(–y); width: var(–size); height: var(–size); /*背景渐变*/ background: radial-gradient(circle closest-side, pink, transparent); /*动画效果*/ transform: translate(-50%, -50%); transition: width 0.2s ease, height 0.2s ease;}/*鼠标经过按钮时*/.mouse-cursor-gradient-tracking:hover:before { –size: 200px;}
javascript:
// 获取按钮元素let btn = document.querySelector(‘.mouse-cursor-gradient-tracking’);// 绑定鼠标移动事件btn.addEventListener(‘mousemove’, e => { // 获取按钮的左,上,右和下分别相对浏览器视窗的位置 let rect = e.target.getBoundingClientRect(); // 计算鼠标坐标相对于按钮左、上的距离 let x = e.clientX – rect.left; let y = e.clientY – rect.top; // 更新背景渐变区域的坐标 btn.style.setProperty(‘–x’, x + ‘px’); btn.style.setProperty(‘–y’, y + ‘px’);});