通过css变量和动画的延迟负值, 实现动画效果

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
  >
  <title>Document</title>
  <style>
    @keyframes move {
      100% {
        transform: translateX(300px);
      }
    }

    :root {
      --delay: 0s;
    }

    .ball {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: tomato;
      animation: move 2s var(--delay) linear;
      animation-play-state: paused;
    }
  </style>
</head>

<body>
  <div class="ball"></div>
  <input
    type="range"
    min="0"
    max="1"
    step="0.01"
    value="0"
  >

  <script>
    const root = document.querySelector(":root")
    const ipt = document.querySelector('input')
    ipt.addEventListener('input', ev => {
      root.style.setProperty('--delay', `${-ev.target.value * 2 + 0.00001}s`)
    })
  </script>
</body>

</html>

 

posted @ 2024-04-09 14:35  深海里的星星i  阅读(22)  评论(0)    收藏  举报