showModalDialog() 曾是 IE 上實作模態對話框的主要手段,能開啟一個「必須先關掉才能操作背後視窗」的子視窗,而且傳值方式相當靈活。以下完整說明它的參數與用法。要注意這套 API 已從標準中移除,僅供維護舊系統時參考。
showModalDialog() // IE 4+ 支援,模態對話框
showModelessDialog() // IE 5+ 支援,非模態對話框
window.showModalDialog() 建立一個顯示 HTML 內容的模態對話框;window.showModelessDialog() 則建立非模態版本。
vReturnValue = window.showModalDialog(sURL [, vArguments] [, sFeatures])
vReturnValue = window.showModelessDialog(sURL [, vArguments] [, sFeatures])
sURL — 必選,字串。指定對話框要顯示的文件 URL。
vArguments — 可選,變體。用來向對話框傳遞參數,型別不限,包含陣列與物件。對話框透過 window.dialogArguments 取得傳入的參數。
sFeatures — 可選,字串。描述對話框外觀,可用一或多個項目,以分號隔開。
以下幾項只用於 HTA,一般網頁不會用到:
透過 vArguments 傳值,型別不限。字串型別最大 4096 字元,也可以傳物件:
// parent.htm
<script>
var obj = new Object();
obj.name = "51js";
window.showModalDialog("modal.htm", obj, "dialogWidth=200px;dialogHeight=100px");
</script>
// modal.htm
<script>
var obj = window.dialogArguments;
alert("您傳遞的參數為:" + obj.name);
</script>
透過 window.returnValue 向開啟對話框的視窗回傳資訊,同樣可以是物件:
// parent.htm
<script>
str = window.showModalDialog("modal.htm", , "dialogWidth=200px;dialogHeight=100px");
alert(str);
</script>
// modal.htm
<script>
window.returnValue = "https://www.jb51.net";
</script>
注意父視窗那行是同步等待的:showModalDialog 會阻塞在該行直到對話框關閉,所以下一行的 alert(str) 才能拿到值。這與非模態版本不同。
IE4 中 dialogHeight 與 dialogWidth 的預設單位是 em,IE5 之後改為 px。為了避免歧異,定義模態對話框時建議一律明確標註 px。