DIV CSS 佈局教程網

封裝 dialog 外掛:Bootstrap 模態視窗的簡易擴充
編輯:關於JavaScript     

用 Bootstrap 模態視窗時,每個彈窗都得在頁面裡寫一段 HTML。若一個頁面要開好幾個彈窗,標籤就會堆得滿山滿谷。於是做了個簡單封裝,把視窗動態產生出來,並額外支援自訂標題、寬高與置中顯示。

可設定的屬性

id:"modal",       // 彈窗 id
title:"dialog",   // 彈窗標題
width:"600",      // 寬度,暫不支援百分比
height:"500",     // 高度,暫不支援百分比
backdrop:true,    // 是否顯示遮罩(同原生)
keyboard:true,    // 是否可用 Esc 關閉(同原生)
remote:"",        // 遠端載入 URL(同原生)
openEvent:null,   // 打開後的回呼
closeEvent:null,  // 關閉後的回呼
okEvent:null      // 點擊確定的回呼

使用方式

方式一:透過 HTML data-* 屬性宣告

<a class="mzDialog" href="#"
   data-remote="test.html"
   data-mtitle="modal1"
   data-id="m1"
   data-width="600"
   data-okEvent="ok()">彈窗demo</a>

方式二:用 JS 初始化

$(".mzDialog").mzDialog();

原始碼

/*------------------------------------------------------
 * 封裝的 dialog 外掛,基於 bootstrap 模態視窗的簡單擴充
 *------------------------------------------------------*/
(function ($) {
  $.fn.mzDialog = function () {
    var defaults = {
      id: "modal",
      title: "dialog",
      width: "600",
      height: "500",
      backdrop: true,
      keyboard: true,
      remote: "",
      openEvent: null,
      closeEvent: null,
      okEvent: null
    };

    var creatDialog = {
      init: function (opts) {
        var _self = this;
        var d = _self.dHtml(opts);
        $("body").append(d);

        var modal = $("#" + opts.id);
        modal.modal(opts);

        // 依標題與底欄高度推算 body 可用高度
        var h = modal.height()
              - modal.find(".modal-header").outerHeight()
              - modal.find(".modal-footer").outerHeight() - 5;

        modal.css({
          'margin-left': opts.width / 2 * -1,
          'margin-top': opts.height / 2 * -1,
          'top': '50%'
        }).find(".modal-body").innerHeight(h);

        modal
          .modal('show')
          .on('hidden', function () {
            modal.remove();
            $(".modal-backdrop").remove();
            if (opts.closeEvent) { eval(opts.closeEvent); }
          })
          .on('shown', function () {
            if (opts.openEvent) { eval(opts.openEvent); }
            $(this).find(".ok").click(function () {
              if (opts.okEvent) {
                var ret = eval(opts.okEvent);
                if (ret) { modal.modal('hide'); }
              }
            });
          });
      },

      dHtml: function (o) {
        return '<div id="' + o.id + '" class="modal hide fade" role="dialog"
                 aria-labelledby="myModalLabel" aria-hidden="true"
                 style="width:' + o.width + 'px;height:' + o.height + 'px;">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"
                            aria-hidden="true">×</button>
                    <h3 id="myModalLabel">' + o.title + '</h3>
                  </div>
                  <div class="modal-body"><p>正在加載...</p></div>
                  <div class="modal-footer">
                    <button class="btn" data-dismiss="modal"
                            aria-hidden="true">取消</button>
                    <button class="btn btn-primary ok">確定</button>
                  </div>
                </div>';
      }
    };

    return this.each(function () {
      $(this).click(function () {
        var opts = $.extend({}, defaults, {
          id: $(this).attr("data-id"),
          title: $(this).attr("data-mtitle"),
          width: $(this).attr("data-width"),
          height: $(this).attr("data-height"),
          backdrop: $(this).attr("data-backdrop"),
          keyboard: $(this).attr("data-keyboard"),
          remote: $(this).attr("data-remote"),
          openEvent: $(this).attr("data-openEvent"),
          closeEvent: $(this).attr("data-closeEvent"),
          okEvent: $(this).attr("data-okEvent")
        });
        creatDialog.init(opts);
      });
    });
  };
})(jQuery);

目前的限制

  • 只有「取消」「確定」兩個按鈕,尚未支援自訂按鈕,需要時得改原始碼。
  • 只支援 data-* 宣告,JS 初始化時無法傳入設定物件。
  • 寬高不建議用百分比。
  • 回呼函數必須是「字串」形式,例如 okEvent:"ok()",括號不能省。

該如何改進

用 eval() 執行字串形式的回呼是很危險的做法,一旦字串來源可被使用者控制,就等於開了 XSS 的後門。比較安全的寫法是允許直接傳函數參照,例如 okEvent: ok,內部用 typeof opts.okEvent === 'function' 判斷後呼叫。

另外,這個版本是針對 Bootstrap 2 寫的(用了 hide fade 與手動處理 modal-backdrop)。在 Bootstrap 3 之後,直接用 $.modal({...}) 傳入完整設定物件,就能少掉大量手刻的樣式計算。

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