彈出視窗時,位置總是左上角跳出來很醜。要讓它優雅地出現在畫面中央,只需依螢幕可用寬高減去視窗尺寸再除以二,算出左上角座標即可。以下是一個可直接運行的範例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS 彈出視窗</title>
</head>
<body>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
function OpenDialog(url, w, h) {
// 依可用工作區計算置中座標
var iTop2 = (window.screen.availHeight - 20 - h) / 2;
var iLeft2 = (window.screen.availWidth - 10 - w) / 2;
var params = 'menubar:no;dialogHeight=' + h + 'px;dialogWidth=' + w + 'px;'
+ 'dialogLeft=' + iLeft2 + 'px;dialogTop=' + iTop2 + 'px;'
+ 'resizable=yes;scrollbars=0;resizeable=0;center=yes;'
+ 'location:no;status:no';
// 先鋪一層半透明遮罩,讓彈窗有層次感
var addDiv = $("<div id='tempDiv' style='left:0px;top:0px;position:absolute;width:100%;height:100%;background:rgba(0,0,0,0.4)!important;filter:alpha(opacity = 40);background:#000;z-index:1000;'></div>");
$(document.body).append(addDiv);
window.open(url, addDiv, params);
}
OpenDialog("https://www.example.com", 300, 300);
</script>
</body>
</html>
這段程式使用的是 window.open 的第三個參數(features 字串),其中 dialogHeight 與 dialogLeft 這類 dialog* 前綴的參數屬於 IE 專屬語法,其他瀏覽器會忽略,置中效果因此在不同瀏覽器上未必一致。
更根本的問題是:現代瀏覽器基於安全考量,對 window.open 開啟的視窗限制嚴格,位置和尺寸參數常被忽略,且容易被打 popup 阻擋器攔下。若你的目標只是「在頁面上顯示一個置中的彈窗」,用 CSS 定位的 modal(例如 position: fixed 加上遮罩層)會相容性更好、可控性更高,也更符合當前的開發慣例。
希望本文對你的 JavaScript 開發有所幫助。