본문 바로가기
카테고리 없음

transition으로 animate되는 요소 추적하기

by 츠키둥구리 2021. 10. 12.

transition으로 top:0에서 top:100px으로 animate되는 요소를 실시간으로 추적할 수 있을까?

animate가 완료되어 top:100px에 도달하는 순간 다른 엑션이 가능한가??

 

가능.

<!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>
      .rect {
        display: block;
        width: 100px;
        height: 100px;
        transition: 1s;
        position: absolute;
        background: red;
        top: 0;
        left: 200px;
      }
    </style>
  </head>
  <body>
    <div class="rect"></div>
    <button>start</button>
    <script>
      const rectEl = document.querySelector(".rect");
      const btnEl = document.querySelector("button");
      btnEl.addEventListener("click", () => {
        //클릭시 .rect에게 top300
        document.querySelector(".rect").style.top = "300px";
        const watchEl = () => {
          const rectTopvalue = rectEl.getBoundingClientRect().top;
          if (rectTopvalue == 300) {
            console.log("목표위치 도달, 추적종료");
            document.querySelector(".rect").style.left = "600px";
            return;
          } else {
            console.log("추적중");
            console.log(rectTopvalue);
            requestAnimationFrame(watchEl);
          }
        };
        watchEl();
      });
    </script>
  </body>
</html>

댓글