原生 alert、confirm 樣式單調又難以客製,實務上很常需要一套外觀統一、可傳入回呼函式的對話框。以下示範如何基於 jQuery UI 的 dialog 元件,封裝出 Alert、Confirm、Error、Warning 四種常用彈窗。
var _alert_iconCss = "tipmsg_icoInfo";
var _confirm_iconCss = "tipmsg_icoConfirm";
var _error_iconCss = "tipmsg_icoError";
var _warning_iconCss = "tipmsg_icoWarning";
function dialogInit(type, msg) {
var iconCss = "";
switch (type) {
case "confirm" : iconCss = _confirm_iconCss; break;
case "error" : iconCss = _error_iconCss; break;
case "warning" : iconCss = _warning_iconCss; break;
default : iconCss = _alert_iconCss; break;
}
var htmlStr = "<div id='" + type + "Div' style='display: none;'><p><span class='" + iconCss + "' style='float:left; margin:0 7px 50px 0;width:35px;height:35px;'></span>" + msg + "</p></div>";
return htmlStr;
}
dialogInit() 會依傳入的類型挑選對應的圖示樣式,並把訊息包成一段 HTML 字串回傳。
function Alert(msg, okCallback) {
var title = "提示";
var type = "alert";
var html = dialogInit(type, msg);
var div = $("body").find("#"+type+"Div");
div.remove();
$('body').append($(html));
var buttons = {"確定" : function () {
if(okCallback) okCallback();
$(this).dialog("close");
}};
$("#"+type+"Div").dialog({
modal : true,
title : title,
buttons : buttons
});
}
function Confirm(msg, okCallback, cancelCallback) {
var title = "確認";
var type = "confirm";
var html = dialogInit(type, msg);
var div = $("body").find("#"+type+"Div");
div.remove();
$('body').append($(html));
var buttons = {"確定" : function () {
if(okCallback) okCallback();
$(this).dialog("close");
},
"取消" : function () {
if(cancelCallback) cancelCallback();
$(this).dialog("close");
}};
$("#"+type+"Div").dialog({
modal : true,
title : title,
buttons : buttons
});
}
function Error(msg, okCallback) {
var title = "錯誤";
var type = "error";
var html = dialogInit(type, msg);
var div = $("body").find("#"+type+"Div");
div.remove();
$('body').append($(html));
var buttons = {"確定" : function () {
if(okCallback) okCallback();
$(this).dialog("close");
}};
$("#"+type+"Div").dialog({
modal : true,
title : title,
buttons : buttons
});
}
function Warning(msg, okCallback) {
var title = "警告";
var type = "warning";
var html = dialogInit(type, msg);
var div = $("body").find("#"+type+"Div");
div.remove();
$('body').append($(html));
var buttons = {"確定" : function () {
if(okCallback) okCallback();
$(this).dialog("close");
}};
$("#"+type+"Div").dialog({
modal : true,
title : title,
buttons : buttons
});
}
四個方法的結構幾乎一致,差別只在標題、類型與按鈕數量。Confirm 多了「取消」按鈕並可傳入取消時的回呼。每次呼叫前都會先移除舊節點再重新插入,避免重複彈出時殘留 DOM。這樣一來,整個專案就能用一致的視覺風格處理各種提示互動了。