在網頁中開啟新視窗時,window.open 是最通用的方法,可指定寬高與位置。若需要強制對話框效果,舊版 IE 可使用 showModalDialog。
以下範例將視窗置中,並針對不同環境提供相容寫法。
function showWin(w, h, url, tag) {
var t = (screen.height - h) / 2;
var l = (screen.width - w) / 2;
window.open(url, tag, 'width=' + w + ',height=' + h + ',top=' + t + ',left=' + l);
}
function openDialog(url, win, width, height) {
var left = (screen.availWidth - width) / 2;
var top = (screen.availHeight - height) / 2;
if (document.all) {
window.showModalDialog(url, win, 'dialogLeft:' + left + 'px;dialogTop:' + top + 'px;dialogWidth:' + width + 'px;dialogHeight:' + height + 'px;');
} else {
window.open(url, win, 'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top);
}
}