js写CSS动画

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      #main {
        width: 100vw;
        height: 100vh;
        background-color: hsl(0deg, 0%, 10%);
        position: relative;
      }
      #box {
        width: 600px;
        height: 140px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
      h1 {
        font-size: 72px;
        text-align: center;
        color: white;
      }
      h2 {
        font-size: 18px;
        text-align: center;
        color: hsl(0deg, 0%, 80%);
        margin-top: 18px;
      }
    </style>
  </head>
  <body>
    <div id="main">
      <div id="box">
        <h1 class="title">Welcome</h1>
        <h2 class="subtitle">JavaScript Web Animations API</h2>
      </div>
    </div>
    <script>
      let title = document.querySelector(".title");
      let subtitle = document.querySelector(".subtitle");
      // 定义动画运行轨迹
      let fadeAndMove = [
        {
          opacity: 0,
          transform: "translateY(-20px)",
        },
        {
          opacity: 1,
          transform: "translateY(0px)",
        },
      ];
      // 定义动画时间对象
      let titletiming = {
        duration: 2000,
        easing: "ease-in-out",
      };
      // 调用动画
      const titleChange = title.animate(fadeAndMove, titletiming);

      let expand = [
        {
          letterSpacing: "-0.5em",
          opacity: 0,
        },
        {
          letterSpacing: "initial",
          opacity: 1,
        },
      ];
      let subtitletiming = {
        duration: titleChange.effect.getComputedTiming().duration / 2,
        easing: "ease-in-out",
      };
      const subTitleChange = subtitle.animate(expand, subtitletiming);
      subTitleChange.pause();
      document.addEventListener("click", () => {
        // playState的状态:  idle 空闲 ,running 正在执行 ,paused 暂停 ,finished 已完成
        if (subTitleChange.playState !== "finished") {
          subTitleChange.play();
        }
      });
    </script>
  </body>
</html>

 

posted @ 2022-08-11 22:46  二王戏木  阅读(108)  评论(0编辑  收藏  举报