jQuery : animate() / setInterval() / clearInterval() 메소드

Study/jQuery

2022.12.13.

  • UI/UX 반응형 웹디자인&웹퍼블리셔 개발자 과정 - DAY 63



Review


 

 

 

 


 

  • UI/UX 반응형 웹디자인&웹퍼블리셔 개발자 과정 - DAY 63

 

 

<keyboard event : keydown, keyCode 알아보기>

 

 

1. 키보드 이벤트

 

이벤트 설명
keydown - 키가 눌릴 때 실행된다.
- 키보드를 꾹 누르고 있을 때도, 입력될 때도 실행된다.
- 웹 브라우저에 따라서 아시아권의 문자(한국어, 중국어, 일본어)를 제대로 처리하지 못하는 문제가 있다.
keypress - 키가 입력되었을 때 실행된다.
- 웹 브라우저에 따라서 아시아권의 문자(한국어, 중국어, 일본어)를 제대로 처리하지 못하는 문제가 있다.
keyup - 키보드에서 키가 떨어질 때 실행된다.
- 특정 키를 꾹 누르고 있으면, 실행되지 않는다.

 

 

 

2. 키보드 이벤트 속성

: 키보드 이벤트가 발생할 때는 이벤트 객체로 어떤 키를 눌렀는지와 관련된 속성이 따라온다.

 

 

이벤트 속성 이름 설명 구체적인 설명
code 입력한 키를 나타내는 문자열 입력한 키를 나타내는 문자열이 들어있다.
keyCode 입력한 키를 나타내는 숫자 입력한 키를 숫자로 나타낸다.
altKey Alt 키를 눌렀는지 Alt 키를 눌렀는지 볼 자료형 값이 들어있다.
ctrlKey Ctrl 키를 눌렀는지 Ctrl 키를 눌렀는지 볼 자료형 값이 들어있다.
shiftKey Shift 키를 눌렀는지 Shift 키를 눌렀는지 볼 자료형 값이 들어있다.

 

 

 

- HTML

 

    <p></p>
    <input type="text" id="user" />
    <br />
    <button class="left">Left</button>
    <button class="right">Right</button>
    <button class="top">Top</button>
    <button class="bottom">Bottom</button>
    <div></div>

 

 

 

- CSS

 

      p {
        margin-bottom: 10px;
      }

      button,
      input {
        padding: 10px 20px;

        font-size: 18px;
      }

      input {
        margin-bottom: 30px;
      }

      div {
        position: relative;
        left: 500px;
        top: 100px;

        width: 50px;
        height: 50px;

        border-radius: 50%;

        background: rgb(217, 184, 224);
      }

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $("button").click(function () {
          $("p").text($(this).text()); // p 태그일 경우
          $("input").val($(this).text()); // input 태그일 경우 text 넣으려면 val 사용
        });

        $(".left").click(function () {
          $("div").css("left", "-=10px");
          // left = left - 10px
          // left -= 10px
        });

        $(".right").click(function () {
          $("div").css("left", "+=10px");
        });

        $(".top").click(function () {
          $("div").css("top", "-=10px");
        });

        $(".bottom").click(function () {
          $("div").css("top", "+=10px");
        });

        $(document).keydown(function (e) {
          console.log(e.keyCode);

          if (e.keyCode == 37) {
            $("div").css("left", "-=10px");
          } else if (e.keyCode == 38) {
            $("div").css("top", "-=10px");
          } else if (e.keyCode == 39) {
            $("div").css("left", "+=10px");
          } else if (e.keyCode == 40) {
            $("div").css("top", "+=10px");
          }
        });
      });
      
    </script>

 

 

 

0


 

 

<jQuery animate() 메소드 알아보기>

 

 

- HTML

 

    <button class="move">move</button>
    <div></div>

 

 

- CSS

 

      p {
        margin-bottom: 10px;
      }

      button {
        padding: 10px 20px;

        font-size: 18px;
      }

      div {
        position: relative;
        left: 500px;
        top: 100px;

        width: 50px;
        height: 50px;

        border-radius: 50%;

        background: rgb(217, 184, 224);
      }

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $(".move").click(function () {
          $("div")
            .animate(
              {
                marginLeft: "100px",
                height: "100px",
                borderRadius: "0",
              },
              1000,
              "swing"
              // position을 적용하지 않으면 움직이지 않음
            )
            .animate({ marginLeft: "100px" })
            .animate({ marginLeft: "200px" });
        });
      });
      
    </script>

 

 

0

 

 

 


 

<jQuery animate() 메소드를 이용해 지그재그 구현해보기>

 

 

- HTML

 

    <button class="move">move</button>
    <div></div>

 

 

- CSS

 

      button {
        margin-bottom: 30px;
      }

      div {
        position: relative;

        width: 50px;
        height: 50px;

        border-radius: 50%;

        background: rgb(217, 184, 224);

        margin-left: 450px;
      }

 

 

left, top을 두니 움직임이 생각처럼 나오지 않아 삭제하고 position: relative; 만 두었다.

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $(".move").click(function () {
          $("div")
            .animate({ left: "100px" })
            .animate({ top: "100px", left: "0" })
            .animate({ left: "100px" });
        });
      });
      
    </script>

 

 

0

 

 


 

 

<jQuery animate() 메소드 예제>

 

 

- HTML

 

    <div class="first"></div>
    <div class="second"></div>
    <button class="move">move</button>

 

 

- CSS

 

      button {
        padding: 10px 20px;

        font-size: 18px;

        margin-top: 50px;
      }

      div {
        position: relative;

        width: 50px;
        height: 50px;

        border-radius: 50%;

        background: rgb(217, 184, 224);

        margin-left: 300px;
      }

 

 

 

 

- jQuery

 

    <script>
    
      $(function () {
        $(".move").click(function () {
          $(".first")
            .animate({ left: "500px" }, 2000, "linear")
            .animate({ left: "0px" }, 2000, "linear");
          $(".second")
            .animate({ left: "500px" }, 2000, "swing")
            .animate({ left: "0px" }, 2000, "swing");
        });
      });
      
    </script>

 

 

0

 

- jQuery

 

    <script>
    
      $(function () {
        function myfnc() {
          $("div").css("backgroundColor", "pink");
        }
        $(".move").click(function () {
          $(".first").animate({ left: "500px" }, 2000, "linear", myfnc);
          $(".second").animate({ left: "500px" }, 2000, "swing", myfnc);
        });
      });

      // 콜백 함수 사용
      /*  $(function () {
        $(".move").click(function () {
          $(".first").animate({ left: "500px" }, 2000, "linear", function () {
            $(".first").css("backgroundColor", "green");
          });

          $(".second").animate({ left: "500px" }, 2000, "linear", function () {
            $(".second").css("backgroundColor", "skyblue");
          });
        });
      });  */
      
    </script>

 

 

0

 

위의 예제에서 jQuery만 병경했다.

 

 


 

 

<콜백 함수 이용, 애니메이션 delay() 메소드 사용 예제>

 

 

- HTML

 

    <p><button class="btn1">Button1</button></p>
    <span class="txt1">500px 이동</span>
    <p>
      <button class="btn2">Button2</button>
    </p>
    <span class="txt2">50px 이동</span>
    <p><button class="btn3">모두 실행</button></p>

 

 

- CSS

 

      button,
      span {
        padding: 10px 20px;

        font-size: 18px;

        margin-top: 50px;
      }

      .txt1 {
        background: pink;
      }

      .txt2 {
        background: skyblue;
      }

 

 

 

- jQuery

 

    <script>
    
      // animate ( {속성},speed,easing,callbak );
      $(function () {
        $(".btn1").click(function () {
          $(".txt1").animate(
            { marginLeft: "500px" },
            1000,
            "linear",
            function () {
              $(".txt1").css("font-size", "30px");
              alert("미션 완료 !");
            }
          );
        });
        // $(".btn1").click();
        // $(".btn1").trigger("click");
        // 함수를 강제로 실행 (호출)

        $(".btn2").click(function () {
          $(".txt2").animate(
            { marginLeft: "50px" },
            1000,
            "linear",
            function () {
              $(".txt2").css("font-size", "30px");
              alert("미션 완료 !");
            }
          );
        });

        $(".btn3").click(function () {
          $(".txt1").animate(
            { marginLeft: "+=500px", fontSize: "30px" },
            1000,
            "linear"
          );
          $(".txt2")
            .delay(2000)
            .animate({ marginLeft: "+=50px" }, 1000, "linear", function () {
              alert("미션 완료");
            });
        });
      });
      
    </script>

 

 

 

0


 

 

<jQuery animate() 메소드 응용 예제>

 

 

- HTML

 

    <div class="box_wrap">
      <div class="box">
        <img src="img/photo6.jpg" alt="photo6" />
      </div>
    </div>
    <button class="left">slideLeft</button>
    <button class="right">slideRight</button>
    <button class="up">slideUp</button>
    <button class="down">slideDown</button>

 

 

- CSS

 

      button {
        padding: 10px 20px;

        font-size: 18px;

        margin: 20px;
      }

      .box_wrap {
        width: 300px;
        height: 400px;

        margin: 0 auto;
      }

      .box {
        width: 300px;

        overflow: hidden;
      }

      img {
        width: 300px;
        height: 400px;

        object-fit: contain;
      }

 

 

 

- jQuery

 

    <script>
    
      // animate ( {속성},speed,easing,callbak );

      $(function () {
        $(".left").click(function () {
          $(".box").animate({ width: "0" }, 800);
        });

        $(".right").click(function () {
          $(".box").animate({ width: "300px" }, 800);
        });

        $(".up").click(function () {
          $(".box").slideUp(800);
        });

        $(".down").click(function () {
          $(".box").slideDown(800);
        });
      });
      
    </script>

 

 

0

box_wrap을 하나 더 만들어야 옆으로 흔들리지 않고 slide가 자연스러워진다.

 

또 여기서 중요한 것은 overflow: hidden; 이다. 

overflow: hidden;을 적용해야 slide가 닫히는 것처럼 보인다.

 

 

 

 

* 이미지 출처

instagram : @postershop.kr

 

 

 


 

 

<jQuery animate() 메소드 응용 예제2>

 

 

- HTML

 

    <p class="txt1">내용 1</p>
    <p class="txt2">내용 2</p>
    <p class="txt3">내용 3</p>

 

 

 

 

- jQuery

 

    <script>
    
      // animate ( {속성},speed,easing,callbak );

      $(function () {
        $(".txt1")
          .animate({ marginLeft: "100px" }, 1000)
          .animate({ marginLeft: "200px" }, 1000)
          .animate({ marginLeft: "300px" }, 1000);

        $(".txt2").delay(3000).animate({ marginLeft: "100px" }, 1000);

        $(".txt3")
          .animate({ marginLeft: "0" }, 1000)
          .animate({ marginLeft: "100px" }, 1000);
      });
      
    </script>

 

 

0

 

 


 

<jQuery animate() 메소드, setInterval() 예제>

 

 

- HTML

 

    <p class="txt1">내용 1</p>
    <p class="txt2">내용 2</p>
    <p class="txt3">내용 3</p>

 

 

 

- jQuery

 

    <script>
    
      // animate ( {속성},speed,easing,callbak );

      $(function () {
        $(".txt1")
          .animate({ marginLeft: "100px" }, 1000)
          .animate({ marginLeft: "200px" }, 1000)
          .animate({ marginLeft: "300px" }, 1000);

        $(".txt2").delay(2000).animate({ marginLeft: "100px" }, 1000);

        /*  setInterval(function () {
          실행구문
        }, 1000);  */

        setInterval(function () {
          $(".txt3")
            .delay(0)
            .animate({ marginLeft: "0" }, 800)
            .animate({ marginLeft: "300px" }, 800);
        }, 1000);
      });
      
    </script>

 

0

 

 


 

 

<jQuery animate() 메소드, setInterval(), clearInterval() 응용 예제>

 

 

 

- jQuery

 

    <script>
    
      // animate ( {속성},speed,easing,callbak );

      $(function () {
        $("body").prepend("<p><span>시작</span><span>정지</span></p>");
        $("span")
          .css("cursor", "pointer")
          .css("border", "1px solid #000")
          .css("padding", "10px 20px")
          .css("margin", "20px");

        /*  setInterval(function () {
          실행 구문
        }, 1000);  */

        /*  clearInterval은 변수 사용이 가능하지만,
        setInterval은 실행 구문으로 적어야 하기 때문에 변수 사용이 불가능  */

        let interval = setInterval(function () {
          $("body").append("<p>Hello world !</p>");
        }, 1000);

        $("span:nth-child(2)").click(function () {
          clearInterval(interval);
        });

        $("span:first").click(function () {
          setInterval(function () {
            $("body").append("<p>Hello world !</p>");
          }, 1000);
        });
      });
      
    </script>

 

 

0

이건 버튼이 처음엔 실행되지만, 반복해서 사용은 불가능하다.

 

선생님께 버튼이 계속 실행되게 하는 방법이 없냐고 질문했는데 잘 모르시는 것 같았다...

 

방법을 찾아내야지,,

 

 


 

 

 

<jQuery animate() 메소드, setInterval(), clearInterval() 응용 예제2>

 

 

- HTML

 

    <div id="tri"></div>
    <button id="stop">Stop</button>

 

 

- CSS

 

      button {
        padding: 10px 20px;
        margin-top: 50px;

        font-size: 18px;
      }

      #tri {
        position: relative;
        top: 0;
        left: 48%;

        width: 0;
        height: 0;

        border-top: 20px solid transparent;
        border-bottom: 20px solid #000;
        border-left: 20px solid transparent;
        border-right: 20px solid transparent;
      }

 

 

 

- jQuery

 

    <script>
    
      // animate ( {속성},speed,easing,callbak );

      $(function () {
        let interval = setInterval(function () {
          $("#tri").animate({ top: "0" }, 400).animate({ top: "10px" }, 400);
        }, 700);
        // animate 시간을 주는 것보다 interval에 주는 시간을 좀 더 여유있게 주는 것이 좋음

        $("#stop").click(function () {
          let txt = $(this).text();
          console.log(txt);

          if (txt == "Stop") {
            $(this).text("Play");

            clearInterval(interval);
          } else if (txt == "Play") {
            $(this).text("Stop");

            interval = setInterval(function () {
              $("#tri")
                .animate({ top: "0" }, 400)
                .animate({ top: "10px" }, 400);
            }, 700);
          }
        });
      });
      
    </script>

 

 

0

선생님께서 원래 stop 버튼만 만들어보라고 하셨는데, 어제 button 안에 text가 바뀌는 것까지

구현해보고 싶어서 응용했다.

 

완성 - !

 

 

반응형