DIV CSS 佈局教程網

showModalDialog 模態對話框完整用法與跨瀏覽器相容處理
編輯:JavaScript綜合知識     

showModalDialog 是 IE 家族提供的 window 方法,用來開啟一個「模態」子視窗。它和 window.open() 最大的差別在於:模態視窗開啟後,父視窗會失去焦點、無法操作,直到子視窗關閉。這讓它非常適合做資料挑選、確認視窗這類必須取得使用者回覆才能繼續的互動。

基本運作

子視窗只要設定 window.returnValue,父視窗就能取得回傳值:

<!-- main.html -->
<script>
function showmodal() {
    // 加上 Math.random() 是為了避免快取
    var ret = window.showModalDialog("sub.html?temp=" + Math.random());
    alert("sub return value is " + ret);
}
</script>
<input id="button1" type="button" value="open sub" onclick="showmodal();">

<!-- sub.html -->
<script>
function returnMain() {
    window.returnValue = "return from sub";
    window.close();
}
</script>
<input id="button1" type="button" value="return and close" onclick="returnMain()">

語法與參數

vReturnValue = window.showModalDialog(sURL[, vArguments][, sFeatures])
  • sURL(必選,字串):對話框要載入的頁面網址。
  • vArguments(可選,變體):傳給對話框的參數,型別不限,陣列或物件皆可。子視窗用 window.dialogArguments 接收。
  • sFeatures(可選,字串):描述外觀,多項以分號分隔。

常用的 sFeatures 設定包括:dialogHeight(高度,不建議小於 100px)、dialogWidth、dialogLeft、dialogTop、center、help、resizable、status、scroll。另有 dialogHide、edge、unadorned 主要用於 HTA,一般網頁較少使用。
建議一律以 px 為單位:IE4 預設单位是 em,IE5 之後才是 px,寫死單位可避免版本差異造成的尺寸錯亂。

跨瀏覽器支援狀況

這是使用這個 API 最必須評估的一點。大致情況如下:

  • IE9、Firefox、Safari:可正常作為模態對話框運作。
  • Chrome:並不會進入模態狀態,父視窗仍可自由取得焦點,效果等同 window.open(),且 returnValue 回傳 undefined。
  • Opera:完全不會彈出視窗。

另一個要注意的細節是:Firefox 下若子視窗被重新整理,window.dialogArguments 會變成 undefined。

讓 Chrome 也能回傳值

思路是改借用父視窗的 returnValue 作為溝通管道。子視窗優先嘗試寫入 window.opener.returnValue,父視窗則在偵測到 undefined 時改讀自己的 returnValue:

<!-- main.html -->
<script>
function showmodal() {
    var ret = window.showModalDialog("sub.html?temp=" + Math.random(), window);
    // for Chrome
    if (ret == undefined) {
        ret = window.returnValue;
    }
    alert("sub return value is " + ret);
}
</script>

<!-- sub.html -->
<script>
function returnMain() {
    if (window.opener != undefined) {
        window.opener.returnValue = "return from sub";
    } else {
        window.returnValue = "return from sub";
    }
    window.close();
}
</script>

如果父視窗本身的 returnValue 另有用途,可以用暫存的方式還原:

var oldValue = window.returnValue;
var newValue = showModalDialog();
window.returnValue = oldValue;

兩點實務提醒

第一,測試 Chrome 的行為時,務必把 html 檔放在 web server(如 Tomcat)上透過 http 網址存取;直接用 file:// 開啟往往測不出正確結果。
第二,也是更根本的建議:在新專案中請不要採用 showModalDialog。它已被標準移除,僅存在於舊 IE 的相容需求場景。今日的對等方案是 <dialog> 元素搭配 showModal(),或任何成熟的 Modal 元件;需要回傳資料時用 Promise 或回呼函式處理,跨瀏覽器行為一致,也不必再寫相容分支。

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