美文网首页
实现按钮涟漪效果

实现按钮涟漪效果

作者: Carlmac | 来源:发表于2021-05-17 15:40 被阅读0次

    看到越来越多的App都会在点击的时候呈现一个涟漪的效果,好奇是怎么实现的。

    效果

    自己想了几个方案,发现都不太好实现。搜集了一些资料之后发现其实并不难,甚至也不需要jQuery。

    先讲讲大体思路:

    1,涟漪由按钮内的子元素去做,这个子元素脱离文档流,故不改变按钮内容的布局

    2,点击按钮时,把点击坐标记录下来,作为涟漪的圆心

    3,创建涟漪子元素,设置好圆心

    4,把它添加到按钮里面去,它被渲染进DOM之后就会播放CSS动画

    5,设置 timeout,在动画时长后把涟漪从按钮里删除

    代码:

    HTML

    <div class="btn">
      <p>Button</p>
    </div>
    

    CSS

    .btn {
      width: 100px;
      height: 50px;
      background-color: green;
      border-radius: 10px;
      position: relative;  /* 必须 */
      overflow: hidden;    /* 必须 */
    }
    
    .btn > p {
      text-align: center;
    }
    
    .btn > span {
      position: absolute;  /* 必须 */
      transform: translate(-50%, -50%);  /* 必须 */
      background: white;
      border-radius: 50%;
      animation: .75s ripple;  /* 必须 */
    }
    
    @keyframes ripple {
      from {
        width: 0px;
        height: 0px;
        opacity: .5;
      }
      to {
        width: 200px;
        height: 200px;
        opacity: 0;
      }
    }
    

    JS

    const btn = document.querySelector('.btn');
    
    btn.addEventListener('mousedown', function(e){
      const left = e.clientX - e.currentTarget.offsetLeft;
      const top = e.clientY - e.currentTarget.offsetTop;
      const rip = document.createElement('span');
      rip.style.left = left + 'px';
      rip.style.top = top + 'px';
      btn.appendChild(rip);
      setTimeout(()=>{rip.remove()}, 750);
    })
    

    源码:
    https://jsbin.com/haxeyonuvo/1/edit?html,css,js,output

    相关文章

      网友评论

          本文标题:实现按钮涟漪效果

          本文链接:https://www.haomeiwen.com/subject/vjujjltx.html