javascript setInterval() , clearInterval()을 이용한 애니메이션 예제2


div를 좌우로 1000px씩 왕복이동 하도록 한 후,
마우스를 hover 했을경우 이동을 정지하도록 그리고
마우스를 out 했을 경우 원래 진행방향으로 이동하도록 짜보았다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
      #box1{
        border: 1px solid red;
        background-color: blue;
        width: 200px;
        height: 200px;
        position: relative;
        left: 100px;
        top: 100px;
      }
    </style>
  </head>
  <body>
    <script type="text/javascript">
    var left =0;
    var timer= setInterval("move_to_left()",50);
    var direct = false;
    // var time2;
    function move_to_left(){
      var box1 = document.getElementById("box1");
      if(left<1000)
        left += 5;
      if(left==1000){
        clearInterval(timer);
        timer = setInterval("move_to_right()",50);
        direct =true;
        }
      console.log(left);
      box1.style.left = left+"px";
    }
    function move_to_right(){
      var box1 = document.getElementById("box1");
      if(left>0)
        left -=5;
      if(left==0){
        clearInterval(timer);
        timer = setInterval("move_to_left()",50);
        direct = false;
      }
      console.log(left);
      box1.style.left = left+"px";
    }
    function stop_move(){
      clearInterval(timer);
    }
    function again_move(){
      if(direct){
        timer = setInterval("move_to_right()",20);
      }else{
        timer = setInterval("move_to_left()",20);
      }

    }

    </script>
      <div id="box1" onmouseover="stop_move()" onmouseout="again_move()">

      </div>
  </body>
</html>

댓글

이 블로그의 인기 게시물

About Kafka Basic

About JVM Warm up

About ZGC

Spring Boot Actuator readiness, liveness probes on k8s

About G1 GC

sneak peek jitpack

About idempotent

C 언어 구조체의 포인터 멤버 변수

Synology NAS에 MariaDB 10에 Mysql workbench로 원격접속하기

About Websocket minimize data size and data transfer cost on cloud