DIV CSS 佈局教程網

jQuery 自訂對話框:取代 alert、confirm、prompt
編輯:JQuery常見問題     

jQuery Alert Dialogs 是一款基於 jQuery 的提示框插件,提供 Alert、Confirm、Prompt 三種對話框,另附一個可嵌入 HTML 的高級範例,樣式完全可自訂。

效果體驗:https:///keleyi/phtml/jqplug/
英文版:https:///keleyi/phtml/jqplug/1.htm

為什麼要換掉原生對話框

這個插件的目標是替代 JavaScript 的 alert()、confirm() 與 prompt(),特色包括:

  1. 可以套用自己的 CSS,讓網站看起來更專業一致。
  2. 對話框標題可自訂,不必再是「此頁面上寫」。
  3. 在 IE7 中避免使用原生 prompt() 帶來的頁面重載問題。
  4. 模擬 Windows 的模態對話框,視窗縮放時會自動重新置中。
  5. 若額外引入 jQuery UI Draggable,對話框還能自由拖動。

三個對外方法

// jAlert( message, [title, callback] )
// jConfirm( message, [title, callback] )
// jPrompt( message, [value, title, callback] )

用法與原生幾乎一致,只是多了一個 callback 接收使用者點選的結果:confirm 與 prompt 會把 true/false 或輸入的字串回傳給你。

設定檔(jquery.alerts.js 重點)

頂部的 $.alerts 物件集中了所有可調參數,任何時候都能從外部讀寫:

(function($) {
  $.alerts = {
    verticalOffset: -75,        //距畫面中心的垂直偏移(px)
    horizontalOffset: 0,       //水平偏移(px)
    repositionOnResize: true,  //視窗縮放時重新置中
    overlayOpacity: .01,       //遮罩透明度
    overlayColor: '#FFF',     //遮罩顏色
    draggable: true,          //是否可拖動(需 UI Draggable)
    okButton: ' OK ',
    cancelButton: ' Cancel ',
    dialogClass: null,        //套用於所有對話框的額外 class

    alert: function(message, title, callback) {
      if( title == null ) title = 'Alert';
      $.alerts._show(title, message, null, 'alert', function(result) {
        if( callback ) callback(result);
      });
    },

    confirm: function(message, title, callback) { /* 同上,type 為 'confirm' */ },
    prompt: function(message, value, title, callback) { /* 同上,type 為 'prompt' */ },

    _show: function(title, msg, value, type, callback) {
      $.alerts._hide();  //先清掉舊的,避免堆疊
      $.alerts._overlay('show');
      $("BODY").append('<div id="popup_container"><h1 id="popup_title"></h1><div id="popup_content"><div id="popup_message"></div></div></div>');

      //IE6 修正:不支援 maxHeight 者用 absolute
      var pos = ('undefined' == typeof (document.body.style.maxHeight)) ? 'absolute' : 'fixed';
      $("#popup_container").css({ position: pos, zIndex: 99999, padding: 0, margin: 0 });

      $("#popup_title").text(title);  //用 text() 而非 html(),避免標題被當成標籤
      $("#popup_content").addClass(type);
      $("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );

      $.alerts._reposition();  //置中
      $.alerts._maintainPosition(true);  //視窗縮放時保持置中

      switch( type ) {
        case 'alert':  //只有確定鈕
        case 'confirm':  //確定 + 取消,分別回傳 true / false
        case 'prompt':  //多一個 text input,回傳輸入值或 null
      }

      if( $.alerts.draggable ) {
        try {
          $("#popup_container").draggable({ handle: $("#popup_title") });
          $("#popup_title").css({ cursor: 'move' });
        } catch(e) { /* 未引入 jQuery UI draggables */ }
      }
    },

    _reposition: function() {
      var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
      var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
      if( top < 0 ) top = 0;
      if( left < 0 ) left = 0;
      $("#popup_container").css({ top: top + 'px', left: left + 'px' });
    },

    _overlay: function(status) { /* show 時鋪滿整個 document 的半透明層 */ },
    _maintainPosition: function(status) { /* bind / unbind window resize */ }
  };

  //快捷函數
  jAlert = function(message, title, callback) { $.alerts.alert(message, title, callback); }
  jConfirm = function(message, title, callback) { $.alerts.confirm(message, title, callback); };
  jPrompt = function(message, value, title, callback) { $.alerts.prompt(message, value, title, callback); };

})(jQuery);

CSS

#popup_container {
  font-family: Arial, sans-serif;
  font-size: 12px;
  min-width: 300px;  /* 對話框最小寬度 */
  max-width: 600px;  /* 超過此寬度自動換行 */
  background: #FFF;
  border: solid 5px #999;
  color: #000;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}
#popup_title {
  font-size: 14px;
  font-weight: bold;
  text-align: center;
  line-height: 1.75em;
  color: #666;
  background: #CCC url(images/title.gif) top repeat-x;
  border: solid 1px #FFF;
  border-bottom: solid 1px #999;
  cursor: default;
}
#popup_content {
  background: 16px 16px no-repeat url(images/info.gif);
  padding: 1em 1.75em;
}
#popup_content.alert   { background-image: url(images/info.gif); }
#popup_content.confirm { background-image: url(images/important.gif); }
#popup_content.prompt  { background-image: url(images/help.gif); }  /* 三種對話框靠 class 換圖示 */
#popup_message { padding-left: 48px; }
#popup_panel  { text-align: center; margin: 1em 0em 0em 1em; }  /* 按鈕區 */
#popup_prompt { margin: .5em 0em; }

需要一併引入

<script type="text/javascript" src="https:///keleyi/pmedia/jquery-1.9.1.min.js"></script>
<script src="https:///keleyi/pmedia/jquery/ui/1.10.3/js/jquery-ui-1.10.3.min.js" type="text/javascript"></script>

讀原始碼可以學到什麼

這支插件雖然規模不大,但示範了幾個值得參考的實作習慣:用 class 而非不同 DOM 結構區分三種對話框,靠 addClass(type) 換背景圖示;置中計算同時考慮 outerHeight/outerWidth,才能把邊框與內距算進去;把 window resize 的綁定與解綁抽成 _maintainPosition,關閉時才不會留下游魂事件;draggable 用 try/catch 包住,沒引入 jQuery UI 時靜默降級而不報錯。

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