DIV CSS 佈局教程網

打造自訂彈窗:取代原生 confirm 與 alert 的實作教學
編輯:關於JavaScript     

原生的 alert() 與 confirm() 雖然方便,但樣式無法客製、按鈕文字也改不了,在手機版網頁上更是突兀。與其勉強遷就,不如自己封裝一個彈窗元件,標題、內文、按鈕文案都能自由決定。

以下示範的 SelfWinsow 建構函式支援五種型態:alert、confirm、confirm2、link 與 talk,其中 confirm 系列會執行你傳入的 callback。

呼叫方式

var win = new SelfWinsow({
  types    : "confirm",              // alert / confirm / confirm2 / link / talk
  slefTitle: "小提醒",                // 彈窗標題
  selfInfo : "確定要移除此項目嗎?",   // 彈窗內文
  selfOk   : "確定",                  // 自訂「確定」按鈕文字
  selfNo   : "取消",                  // 自訂「取消」按鈕文字
  callback : fn                      // confirm / confirm2 / talk 專用的回呼函式
});

樣式(節錄重點)

<style>
*{ padding: 0; margin: 0; }
#selfWinsow{
  width: 60%; margin: 0 20%; background: #fff;
  position: fixed; top: 35%;
  border: 1px solid #ccc; padding: 0 2% 2% 2%;
}
#slefClose{
  width: 25px; height: 25px; position: absolute;
  right: 1rem; top: 0.4rem; z-index: 9999; cursor: pointer;
}
#slefClose::after{
  position: absolute; width: 30px; height: 30px;
  content: "×"; font-size: 2.5rem; line-height: 30px;
}
#selfWinsow h2{
  font-size: 1rem; border-bottom: 1px solid #ccc;
  line-height: 100%; padding: 1rem 0;
}
#selInfo{ font-size: 0.95rem; line-height: 2.1rem; padding: 0.5rem; }
#selfBtBox{ padding: 1rem; margin: 0 auto; border: 1px solid #ccc; overflow: hidden; }
.selfBt{
  padding: 0.8rem 2%; background: #323434; color: #fff;
  float: left; line-height: 100%; text-align: center; cursor: pointer;
}
.selfBtDouble{ width: 46%; }
.selfBtSingle{ color: #fff; width: 100%; padding: 0.8rem 0; }
#selfOk{ background: #323434; }
#selfNo, #linkTo2{ background: #eeeeee; color: #555555; }
#selfBack{ width: 100%; background: rgba(0,0,0,.6); }
</style>

核心邏輯

var SelfWinsow = function (settings) { this.init(settings); };

SelfWinsow.prototype = {
  init: function (settings) {
    this.opts = {
      types   : "",
      slefTitle: "",
      selfInfo: (typeof settings == "string") ? settings : "確定要繼續嗎?",
      selfOk  : "繼續操作",
      selfNo  : "返回上一頁"
    };
    this.setting(settings);
    if (typeof settings == "string") { this.opts.selfInfo = settings; }

    if (settings == "" || settings == undefined || settings == null) {
      this.selfAlert();
    } else if (settings.types == "confirm") {
      this.selfConfirm();
    } else if (settings.types == "confirm2") {
      this.selfConfirm2();
    } else if (settings.types == "link") {
      this.selfLink();
    } else if (settings.types == "talk") {
      this.selfMobileTalk();
    } else {
      this.selfAlert();
    }
  },

  // confirm 視窗:兩個按鈕
  selfConfirm: function () {
    var _this = this;
    var html = "<div id='selfWinsow'><div id='slefClose'><\/div>"
      + "<h2 id='slefTitle'>" + _this.opts.slefTitle + "<\/h2>"
      + "<p id='selInfo'>" + _this.opts.selfInfo + "<\/p>"
      + "<div id='selfOk' class='selfBt selfBtDouble'>" + _this.opts.selfOk + "<\/div>"
      + "<div id='selfNo' class='selfBt selfBtDouble'>" + _this.opts.selfNo + "<\/div>"
      + "<\/div>";
    this.createMask(html);
    this.selfEvents();
  },

  // alert 視窗:只有一個按鈕
  selfAlert: function () {
    var _this = this;
    var html = "<div id='selfWinsow'><div id='slefClose'><\/div>"
      + "<h2 id='slefTitle'>" + _this.opts.slefTitle + "<\/h2>"
      + "<p id='selInfo'>" + _this.opts.selfInfo + "<\/p>"
      + "<div id='selfOk' class='selfBt selfBtSingle'>" + _this.opts.selfOk + "<\/div>"
      + "<\/div>";
    this.createMask(html);
    this.selfEvents();
  },

  selfConfirm2: function () { /* 結構同 selfAlert */ },

  // 帶連結的視窗
  selfLink: function () {
    var _this = this;
    var html = "<div id='selfWinsow'><div id='slefClose'><\/div>"
      + "<h2 id='slefTitle'>" + _this.opts.slefTitle + "<\/h2>"
      + "<p id='selInfo'>" + _this.opts.selfInfo + "<\/p>"
      + "<a id='selfOk' href='" + _this.opts.linkTo1 + "' class='selfBt selfBtDouble'>" + _this.opts.selfOk + "<\/a>"
      + "<a id='linkTo2' href='" + _this.opts.linkTo2 + "' class='selfBt selfBtDouble'>" + _this.opts.selfNo + "<\/a>"
      + "<\/div>";
    this.createMask(html);
    this.selfEvents();
  },

  selfMobileTalk: function () { /* 含 textarea 的輸入型彈窗 */ },

  selfEvents: function () {
    this.selfOk();
    var selfNo = document.getElementById('selfNo');
    selfNo && this.slefNo();
  },

  // 「確定」按鈕
  selfOk: function () {
    var _this = this, type = this.opts.types, bt = true;
    function selfOkFun(e) {
      var e = e || window.event;
      var el = e.scrElement || e.target;
      if (el.id == "selfOk" || el.tagName == "IMG") {
        if (type == "alert") {
          _this.selfRemoveBack();
        } else if (type == "confirm" || type == "talk" || type == "confirm2") {
          if (bt) { _this.opts.callback(); } else { return false; }
          _this.selfRemoveBack();
          bt = false;
        }
      }
    }
    document.removeEventListener('click', selfOkFun, false);
    document.addEventListener('click', selfOkFun, false);
  },

  // 建立遮罩
  createMask: function (html) {
    var selfBack = document.getElementById("selfBack");
    if (selfBack) { return false; }
    selfBack = document.createElement('div');
    selfBack.id = "selfBack";
    selfBack.style.position = "fixed";
    selfBack.style.top = "0";
    selfBack.style.left = "0";
    selfBack.style.right = "0";
    selfBack.style.bottom = "0";
    document.body.appendChild(selfBack);
    selfBack.innerHTML = html;
    this.slefClose();
  },

  slefClose: function () { /* 點擊右上角 × 關閉 */ },
  slefNo: function () { /* 點擊「取消」關閉並清空 callback */ },

  selfRemoveBack: function () {
    try {
      var selfBack = document.getElementById('selfBack');
      document.body.removeChild(selfBack);
    } catch (e) {}
  },

  exetends: function (a, b) {
    for (var attr in b) { a[attr] = b[attr]; }
  },
  setting: function (settings) { this.exetends(this.opts, settings); }
};

這份寫法有幾個值得學的地方:用 setting() 搭配 exetends() 合併預設值與自訂參數,讓元件易於擴充;用事件委派掛在 document 上,避免重複綁定;關閉時把 callback 清空,防止第二次開啟時觸發到舊的函式。

當然,若你不需要這麼多變化,直接寫幾行 CSS 加上 hidden 屬性切換顯示,也能達到同樣效果。而若要處理複雜的互動流程,成熟的前端框架或元件庫會比手刻更省心。

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