利用 CSS 变量实现令人震惊的鼠标悬浮效果

这个动画是将鼠标移动到订阅按钮上移动光标会显示相应的彩色渐变。这个想法很简单,但是它能使这个按钮脱颖而出,人们一下子就注意到它了,增加了点击的概率。


640?wx_fmt=gif&wxfrom=5&wx_lazy=1


怎样才能达到这个效果,使我们的网站脱颖而出呢?其实,它并不像你想象的那么难!

追踪位置


我们要做的第一件事就是获取到鼠标的位置。

    document.querySelector('.button').onmousemove = (e) => {
     
      const x = e.pageX - e.target.offsetLeft

      const y = e.pageY - e.target.offsetTop

     
      e.target.style.setProperty('--x', `${ x }px`)

      e.target.style.setProperty('--y', `${ y }px`)
   
    }
  1. 选择元素,等待,直到用户将鼠标移过它;

  2. 计算相对于元素的位置;

  3. 将坐标存在CSS的变量中。

是的,仅仅9行代码就让你能获知用户放置鼠标的位置,通过这个信息你能达到意想不到的效果,但是我们还是先来完成CSS部分的代码。

动画渐变


我们先将坐标存储在CSS变量中,以便能够随时使用它们。


    .button {

      position: relative;

      appearance: none;

      background: #f72359;

      padding: 1em 2em;

      border: none;

      color: white;

      font-size: 1.2em;

      cursor: pointer;

      outline: none;

      overflow: hidden;

      border-radius: 100px;

     

      span {

        position: relative;

      }

     

      &::before {

        --size: 0;  

     

        content: '';

        position: absolute;

        left: var(--x);

        top: var(--y);

        width: var(--size);

        height: var(--size);

        background: radial-gradient(circle closest-side, #4405f7, transparent);

        transform: translate(-50%, -50%);

        transition: width .2s ease, height .2s ease;

      }

     

      &:hover::before {

        --size: 400px;

      }

    }

1. 将文本包裹在一个 span 中,防止渐变层覆盖到文字上方

2. 初始 widthheight0px 并且当鼠标悬浮在按钮上时将它们增加到 400px 。不要忘记设置 transition 让它有个渐入的效果

3. 使用 JS 中设置坐标跟随鼠标

4. 应用一个 radial-gradientbackground 上并使用 closest-side circleclosest-side 使得 background 充满整个 before 但又没有超出它。

效果

就这样,添加缺少的 HTML 就可以了:

<button class="button">
	<span>Hover me I'm awesome</span>
</button>







猜你喜欢

转载自blog.csdn.net/gjc_csdn/article/details/80538914