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

Cách căn giữa cửa sổ popup trên màn hình bằng JavaScript

Để căn giữa cửa sổ popup trên màn hình, bạn có thể chạy code sau:

Ví dụ

<!DOCTYPE html>
<html>
  <body>
    <script>
      function myPopup(myURL, title, myWidth, myHeight) {
        var left = (screen.width - myWidth) / 2;
        var top = (screen.height - myHeight) / 4;
        var myWindow = window.open(myURL, title,
          'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + myWidth + ', height=' + myHeight + ', top=' + top + ', left=' + left);
      }
    </script>
    <button onclick="myPopup('https://www.qries.com', 'web', 1050, 550);">Open Qries.com</button>
  </body>
</html>

Lưu ý: Trình duyệt hiện đại thường chặn window.open nếu không do hành động người dùng trực tiếp (click). Tính toán top chia 4 không chính xác, nên chia 2 cho cả width và height.