SeouliteLab

jQuery .resize() 메서드: 화면 크기 변화 감지하기 본문

프로그래밍

jQuery .resize() 메서드: 화면 크기 변화 감지하기

Seoulite Lab 2024. 4. 4. 09:06

예제 1: 브라우저 창 크기 변경 감지하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .resize() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $(window).resize(function(){
        var width = $(window).width();
        var height = $(window).height();
        $("#result").text("창의 너비: " + width + ", 높이: " + height);
      });
    });
  </script>
</head>
<body>
  <p id="result">창의 크기가 변경될 때 여기에 결과가 표시됩니다.</p>
</body>
</html>

설명: 이 예제는 브라우저 창의 크기가 변경될 때마다 해당 창의 너비와 높이를 표시합니다.

예제 2: 요소 크기 변경 감지하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .resize() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("#box").resize(function(){
        var width = $(this).width();
        var height = $(this).height();
        $("#result").text("상자의 너비: " + width + ", 높이: " + height);
      });
    });
  </script>
  <style>
    #box {
      width: 200px;
      height: 200px;
      background-color: lightblue;
    }
  </style>
</head>
<body>
  <div id="box"></div>
  <p id="result">상자의 크기가 변경될 때 여기에 결과가 표시됩니다.</p>
</body>
</html>

설명: 이 예제는 상자 요소의 크기가 변경될 때마다 해당 요소의 너비와 높이를 표시합니다.

예제 3: 리사이즈 이벤트 핸들러 해제하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .resize() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      function resizeHandler() {
        $("#result").text("창의 크기가 변경되었습니다.");
      }

      $(window).resize(resizeHandler);

      $("#unbindButton").click(function(){
        $(window).off("resize", resizeHandler);
        $("#result").text("리사이즈 이벤트 핸들러가 해제되었습니다.");
      });
    });
  </script>
</head>
<body>
  <p id="result">창의 크기가 변경되면 여기에 결과가 표시됩니다.</p>
  <button id="unbindButton">리사이즈 이벤트 핸들러 해제</button>
</body>
</html>

설명: 이 예제는 리사이즈 이벤트 핸들러를 등록하고, 버튼을 클릭하여 해당 핸들러를 해제하는 방법을 보여줍니다.

예제 4: 특정 요소 크기 변화 감지하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .resize() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("#resizable").resizable({
        resize: function(event, ui){
          var width = ui.size.width;
          var height = ui.size.height;
          $("#result").text("너비: " + width + ", 높이: " + height);
        }
      });
    });
  </script>
  <style>
    #resizable {
      width: 150px;
      height: 150px;
      padding: 0.5em;
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <div id="resizable"></div>
  <p id="result">크기가 변경될 때 여기에 결과가 표시됩니다.</p>
</body>
</html>

설명: 이 예제는 jQuery UI를 사용하여 크기가 조정 가능한 요소의 크기 변화를 감지하고 결과를 표시합니다.