使用promise完成div向不同方向移动

48 阅读1分钟
<!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>
      div {
        width: 200px;
        height: 200px;
        background: olivedrab;
      }
    </style>
  </head>
  <body>
    <div></div>
  </body>
  <script>
    const div = document.querySelector("div");
    // 定义一个移动函数
    // 这个函数要做的是,传入一个对象,就移动x和y
    // 并且返回一个成功态的Promise()
    const move = (obj, x, y) => {
      obj.style.transform = `translate(${x}px,${y}px)`;
      //   promise里面是 成功态,但不是立即转为成功态
      // 而是当obj执行完了(ontransitionend)
      return new Promise((resolve) => {
        obj.ontransitionend = () => {
          resolve();
        };
      });
    };
    // 开始写点击逻辑
    div.onclick = function () {
      // 点击一次开始执行move()函数
      // move函数会返回一个promise,所以可以直接.then().then()
      move(this, 150, 0)
        .then(() => {
          // 执行到第一个then,继续执行move
          return move(this, 150, 150);
        })
        .then(() => {
          return move(this, 0, 150);
        })
        .then(() => {
          return move(this, 0, 0);
        });
    };
  </script>
</html>