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

Phương thức window.resizeBy() trong HTML

Phương thức window.resizeBy(deltaWidth, deltaHeight) thay đổi kích thước cửa sổ tương đối so với kích thước hiện tại (cộng/trừ pixel).

Cú pháp

window.resizeBy(deltaWidth, deltaHeight)

Ví dụ

<!DOCTYPE html>
<html>
<style>
  body { color: #000; height: 100vh; background-color: #8BC6EC; background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%) no-repeat; text-align: center; }
  .btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 30%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
</style>
<body>
<h1>Demo window.resizeBy()</h1>
<button onclick="openWin()" class="btn">Mở cửa sổ nhỏ (80x80)</button>
<button onclick="resizeWin()" class="btn">Mở rộng +100x+100</button>
<script>
  var myWindow;
  function openWin() {
    myWindow = window.open('', '', 'width=80,height=80');
    myWindow.document.write('<p>Cửa sổ con 80x80px</p>');
  }
  function resizeWin() {
    if (myWindow && !myWindow.closed) {
      myWindow.resizeBy(100, 100); // Tăng 100px rộng, 100px cao
      myWindow.focus();
      myWindow.document.write('<p>Đã mở rộng +100x+100px</p>');
    } else {
      alert('Hãy mở cửa sổ trước!');
    }
  }
</script>
</body>
</html>

Kết quả

  1. Mở popup 80x80.
  2. Nhấn "Mở rộng" → popup thành 180x180. Nhấn lại → 280x280...

Khác với resizeTo (tuyệt đối), resizeBy là tương đối. Cùng hạn chế: chỉ hoạt động trên popup, không trên tab chính. Dùng window.innerWidth/Height để đọc kích thước viewport.