Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cross-browser window resize event trong JavaScript

Để xử lý sự kiện resize cửa sổ cross-browser, dùng addEventListener(). Code sau cho kích thước cửa sổ hiện tại:

Ví dụ

<!DOCTYPE html>
<html>
  <head>
    <style>
      div { margin-top: 10px; padding: 10px; background-color: #1E9E5D; width: 50%; }
      span { font-size: 50px; }
    </style>
    <script>
      window.addEventListener('resize', display);
      function display() {
        document.querySelector('.width').innerText = document.documentElement.clientWidth;
        document.querySelector('.height').innerText = document.documentElement.clientHeight;
      }
      display(); // Gọi lần đầu
    </script>
  </head>
  <body>
    <div>
      <span>Width= <span class="width"></span></span><br />
      <span>Height= <span class="height"></span></span>
    </div>
  </body>
</html>

Lưu ý: Sự kiện resize fire liên tục khi kéo thả. Nên dùng debounce hoặc requestAnimationFrame để tối ưu hiệu năng.