DIV CSS 佈局教程網

js showModalDialog 參數詳解與父子視窗雙向傳值範例
編輯:關於JavaScript     

相容性提醒:此 API 為 IE 專屬,其他瀏覽器已不支援,僅供維護舊系統參考。

基本介紹

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 可選參數,型別為字串。用來描述對話框的外觀等資訊,可用以下一或多個,以分號「;」隔開:

1. dialogHeight:  對話框高度,不小於 100px
2. dialogWidth:   對話框寬度
3. dialogLeft:    距螢幕左側的距離
4. dialogTop:     距螢幕上方的距離
5. center:  { yes | no | 1 | 0 }  是否居中,預設 yes,仍可指定高寬
6. help:    { yes | no | 1 | 0 }  是否顯示說明按鈕,預設 yes
7. resizable: { yes | no | 1 | 0 } [IE5+] 是否可改變大小,預設 no
8. status:  { yes | no | 1 | 0 } [IE5+] 是否顯示狀態列,模態預設 no、非模態預設 yes
9. scroll:  { yes | no | 1 | 0 | on | off } 是否顯示捲軸,預設 yes

以下屬性用在 HTA 中,一般網頁不會使用:

10. dialogHide: { yes | no | 1 | 0 | on | off } 列印或預覽時是否隱藏,預設 no
11. edge:  { sunken | raised }  對話框邊框樣式,預設 raised
12. unadorned: { yes | no | 1 | 0 | on | off }  預設 no

參數傳遞

1. 傳入參數

透過 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>

2. 回傳值給父視窗

透過 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("modal.htm",, "dialogWidth=...") 時,中間那兩個逗號是必要的,代表 vArguments 留空。若誤寫成冒號分隔 features(dialogWidth:200px),該設定不會生效,必須用等號。
  • 設定值需帶單位:IE5 之後 dialogHeight、dialogWidth 的單位是 px,建議明確寫出 200px。
  • returnValue 必須在關閉前設定:先指定 window.returnValue,再呼叫 window.close(),順序顛倒會導致父視窗收到空值。
  • 模態視窗會阻斷執行緒:showModalDialog 是同步阻斷的,下一行程式碼要等對話框關閉後才執行,這也是它能直接回傳值的原因。

替代方案

新專案請改用 <dialog> 元素:

const dlg = document.querySelector('#myDialog');
dlg.showModal();
// 關閉時
dlg.returnValue = "someValue";
dlg.close();
// 讀取結果
dlg.addEventListener('close', () => console.log(dlg.returnValue));

若對話框內容是獨立頁面(對應原本的 sURL),可用 iframe 嵌入 <dialog>,並以 postMessage 與 iframe 溝通,再用 Promise 包裝成非同步呼叫,就能得到與 showModalDialog 類似但跨瀏覽器可用的寫法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved