2019-08-16
描述
一个渐变跟随着光标移动的效果。
HTML
<button class="mouse-cursor-gradient-tracking"><span>Hover me</span></button>
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;
}
.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
var btn = document.querySelector('.mouse-cursor-gradient-tracking')
btn.onmousemove = function(e) {
  var x = e.pageX - btn.offsetLeft - btn.offsetParent.offsetLeft
  var y = e.pageY - btn.offsetTop - btn.offsetParent.offsetTop
  btn.style.setProperty('--x', x + 'px')
  btn.style.setProperty('--y', y + 'px')
}
Demo
说明
overflow: hidden防止渐变效果溢出该元素范围position: relative相对于伪元素而言,为其在父元素上重新建立一个笛卡尔坐标系::before定义一个伪元素position: absolute使伪元素脱离文档流的布局,使其能够相对于他的父亲进行绝对定位radial-gradient()函数可以创建一个 2D 的图形,用来展示由原点辐射开的颜色渐变transform: translate(-50%, -50%)让元素的中心点偏移到光标位置transition当高和宽变化时,使用 ease 时间函数进行 0.2 秒的过渡--size声明一个局部变量var(--x)表示在 CSS 中使用变量style.setProperty('--x', x + 'px')为使用 JavaScript 方法改变元素中所使用到的变量e.pageX - btn.offsetLeft - btn.offsetParent.offsetLeft可以计算出当前鼠标距离按钮元素的 x 轴距离
浏览器支持
支持率:91.6%
支持情况:https://caniuse.com/#feat=css-variables
⚠️:需要 JavaScript
        
                
                ME!
            
                
                链滴