美文网首页
实现按钮点击水波纹效果

实现按钮点击水波纹效果

作者: fyAgent | 来源:发表于2019-08-23 11:12 被阅读0次
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,
    body,
    #app {
      height: 100%;
      width: 100%;
      position: relative;
    }

    .container {
      width: 200px;
      height: 100px;
      border: 1px solid;
      position: absolute;
      overflow: hidden;
      top: 0;
      bottom: 0;
      right: 0;
      left: 0;
      margin: auto;
    }

    .start {
      position: absolute;
      border-radius: 50%;
      background: red;
      transition-property: transform, background-color, opacity;
      transform: scale(0);
    }

    .end {
      transform: scale(1) !important;
      opacity: 0;
    }
  </style>
  <div id="app">
    <div class="container">

    </div>
  </div>
  <script>
    const container = document.querySelector('.container')

    container.addEventListener('click', e => {
      const offsetX = e.clientX - e.currentTarget.offsetLeft;
      const offsetY = e.clientY - e.currentTarget.offsetTop;
      const { offsetHeight, offsetWidth } = e.currentTarget;
      const lx = Math.max(offsetX, offsetWidth - offsetX);
      const ly = Math.max(offsetY, offsetWidth - offsetY);
      const r = Math.sqrt(Math.pow(lx, 2) + Math.pow(ly, 2));
      startAnimation(container, offsetX, offsetY, r);
    })

    async function startAnimation(el, x, y, r, duration = 1) {
      const styles = {
        width: 2 * r + 'px',
        height: 2 * r + 'px',
        left: x - r + 'px',
        top: y - r + 'px',
        transitionDuration: `${duration}s`
      };
      const div = document.createElement('div');
      div.className = 'start';
      Object.keys(styles).forEach(key => {
        div.style[key] = styles[key];
      })
      el.appendChild(div);
      const nextTick = () => new Promise(res => requestAnimationFrame(res));
      const sleep = (duration) => new Promise(res => setTimeout(res, duration));
      await nextTick();
      div.classList.add('end');
      await sleep(duration * 1000);
      el.removeChild(div);
    }
  </script>
</body>

</html>

相关文章

网友评论

      本文标题:实现按钮点击水波纹效果

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