使用 `window.open()` 開啟新視窗並指定座標與尺寸,常用於公告、登入框、說明頁等不需完整瀏覽器介面的場景。
window.open(url, target, features)
// url: 目標網址
// target: 視窗名稱(_blank, _self, _parent, 或自訂名稱)
// features: 逗號分隔的特性字串,如 "width=400,height=300,left=100,top=100"
| 參數 | 說明 | 備註 |
|---|---|---|
| width / height | 視窗寬高(像素) | 最小值受瀏覽器限制(通常 100px) |
| left / top / screenX / screenY | 視窗左上角座標 | 相對螢幕左上角 |
| resizable | 是否可調整大小 | yes/no 或 1/0 |
| scrollbars | 是否顯示捲軸 | yes/no |
| status | 是否顯示狀態列 | 現代瀏覽器多忽略 |
| toolbar / menubar / location | 工具列/選單列/網址列 | 現代瀏覽器多強制顯示 |
function openCentered(url, w, h, name) {
var left = (screen.availWidth - w) / 2;
var top = (screen.availHeight - h) / 2;
var features = 'width=' + w + ',height=' + h + ',left=' + left + ',top=' + top +
',resizable=yes,scrollbars=yes';
return window.open(url, name || '_blank', features);
}
// 使用
document.getElementById('btn').addEventListener('click', function() {
openCentered('https://example.com', 600, 400, 'popupWin');
});
彈出視窗易被攔截器攔截、行動裝置體驗差、無法與父頁面共享狀態。建議改用:
<dialog id="myDialog">
<h3>公告標題</h3>
<p>這是一個模態對話框,不會被攔截器攔截。</p>
<button id="closeBtn">關閉</button>
</dialog>
<button id="openBtn">開啟公告</button>
<script>
var dialog = document.getElementById('myDialog');
document.getElementById('openBtn').onclick = function() { dialog.showModal(); };
document.getElementById('closeBtn').onclick = function() { dialog.close(); };
// 點擊背景關閉
dialog.addEventListener('click', function(e) {
if (e.target === dialog) dialog.close();
});
</script>