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

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

Phương thức window.resizeTo(width, height) thay đổi kích thước cửa sổ trình duyệt đến kích thước tuyệt đối chỉ định (tính bằng pixel).

Cú pháp

window.resizeTo(width, height)

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.resizeTo()</h1>
<button onclick="openWin()" class="btn">Mở cửa sổ nhỏ (80x80)</button>
<button onclick="resizeWin()" class="btn">Resize thành 400x300</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.resizeTo(400, 300);
      myWindow.focus();
      myWindow.document.write('<p>Đã resize thành 400x300px</p>');
    } else {
      alert('Hãy mở cửa sổ trước!');
    }
  }
</script>
</body>
</html>

Kết quả

  1. Nhấn "Mở cửa sổ nhỏ" → popup 80x80px.
  2. Nhấn "Resize thành 400x300" → popup mở rộng.

⚠️ Hạn chế: Trình duyệt hiện đại chặn resizeTo() trên tab/window chính (chỉ cho phép trên popup do window.open tạo). Cần user gesture (click) để mở popup.