回调函数实现div向上下左右移动的效果

96 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Promise 是什么</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      #box {
        width: 300px;
        height: 300px;
        background-color: olivedrab;
        transition: all 0.5s; /* css里面的过渡属性,包括要执行的名称,时间,和曲线*/
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
  </body>
  <script>
    // 点击的时候,改变transform属性
    var div = document.getElementById("box");

    div.onclick = function () {
      /* transform属性是改变translate(),这里面有2个参数,一个是x轴的值,一个是y轴的值 */
      div.style.transform = "translate(150px,0px)"; /* 向右跑100px */
      // 1秒之后再向下跑100px
      setTimeout(function () {
        div.style.transform = "translate(150px,150px)";
        // settimeout里面继续写settimeout
        setTimeout(function () {
          div.style.transform = "translate(0px,150px)";
          // 继续写settimeout
          setTimeout(function () {
            div.style.transform = "translate(0px,0px)";
          }, 500);
        }, 500);
      }, 500);
      //  再过 1秒之后继续向左
    };

    // 另一种方法是使用ontransitionend方法,规定这个点击事件结束以后要做的事
    div.onclick = function () {
      div.style.transform = "translate(150px,0px)";
      div.ontransitionend = function () {
        div.style.transform = "translate(150px,150px)";
        // 第一个ontransitionend执行完了以后接着执行ontransitionend
        div.ontransitionend = function () {
          div.style.transform = "translate(0px,150px)";
          //   这个也一样,执行完接着执行,函数里面套函数
          div.ontransitionend = function () {
            div.style.transform = "translate(0px,0px)";
          };
        };
      };
    };
  </script>
</html>