如何使用css實(shí)現(xiàn)漸變跟隨鼠標(biāo)光標(biāo)的懸停效果。如下圖:
實(shí)現(xiàn)思路:
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;}/*按鈕漸變背景,這里使用偽類實(shí)現(xiàn),并且使用transform動(dòng)畫*/.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); /*動(dòng)畫效果*/ transform: translate(-50%, -50%); transition: width 0.2s ease, height 0.2s ease;}/*鼠標(biāo)經(jīng)過按鈕時(shí)*/.mouse-cursor-gradient-tracking:hover:before { –size: 200px;}
javascript:
// 獲取按鈕元素let btn = document.querySelector(‘.mouse-cursor-gradient-tracking’);// 綁定鼠標(biāo)移動(dòng)事件btn.addEventListener(‘mousemove’, e => { // 獲取按鈕的左,上,右和下分別相對(duì)瀏覽器視窗的位置 let rect = e.target.getBoundingClientRect(); // 計(jì)算鼠標(biāo)坐標(biāo)相對(duì)于按鈕左、上的距離 let x = e.clientX – rect.left; let y = e.clientY – rect.top; // 更新背景漸變區(qū)域的坐標(biāo) btn.style.setProperty(‘–x’, x + ‘px’); btn.style.setProperty(‘–y’, y + ‘px’);});