jDialog 是一個輕量、多功能的 jQuery 彈出框插件,支援 alert/confirm/message/iframe/tip/dialog 等多種模式,相容性好、API 簡潔。本文整理其核心用法、參數配置與原始碼關鍵邏輯。
<script src="jquery.min.js"></script>
<script src="jdialog.js"></script>
<link rel="stylesheet" href="jdialog.css">
// 1. 簡單提示 (alert)
$.jDialog({ content: '操作成功!', timer: 2000 }); // 2秒自動關閉
// 2. 確認框 (confirm)
$.jDialog({
title: '確認刪除',
content: '確定要刪除此筆資料嗎?',
ok: function() { console.log('用戶點擊確認'); return true; },
cancel: function() { console.log('用戶取消'); return true; }
});
// 3. 自訂按鈕對話框
$.jDialog({
title: '編輯資料',
content: '<input id="name" placeholder="姓名">',
buttons: [
{ title: '儲存', callback: function() { save(); return true; } },
{ title: '取消', callback: function() { return true; } }
],
showbuttons: true
});
// 4. Tip 提示 (帶三角箭頭)
$.jTip({ content: '這是提示文字', posX: 100, posY: 200 });
| 參數 | 型別 | 預設值 | 說明 |
|---|---|---|---|
| title | String | '' | 標題文字,空則不顯示標題列 |
| content | String/HTML | '這是一個JasUI-Dialog插件' | 內容區 HTML |
| width | Number | 350 | 對話框寬度 (px) |
| height | Number | 0 (自適應) | 高度,0 為自動 |
| timer | Number | 0 | 自動關閉毫秒數,0 不自動關閉 |
| showbuttons | Boolean | false | 是否顯示自訂按鈕區 |
| buttons | Array | [] | 自訂按鈕 [{title, callback}] |
| okval | String | '確認' | 確定按鈕文字 |
| ok | Function | function(){return false} | 確定回調,回傳 false 關閉 |
| cancelval | String | '取消' | 取消按鈕文字 |
| cancel | Function | function(){return false} | 取消回調 |
| showclose | Boolean | true | 是否顯示右上角關閉鈕 |
| close | Function | function(){} | 關閉後回調 |
| theme | String | '' | 主題類名 (如 'blue', 'red') |
var jDialogId = [];
var id = parseInt(Math.random() * 1000 + 1);
while ($.inArray(id, jDialogId) != -1) id = parseInt(Math.random() * 1000 + 1);
jDialogId.push(id);
確保同頁多實例 ID 不衝突,關閉時從陣列移除。
var _objdiv = "<div id='j-dialog-" + id + "' class='j-dialog ...'>...";
$("body").append(_objdiv);
var _obj = $('#j-dialog-' + id);
字串拼接建構完整結構:header(標題+關閉鈕) + content + footer(按鈕)。
_obj.css({ width: options.width, height: options.height,
'margin-top': -options.height/2, 'margin-left': -options.width/2 });
_obj.animate({ top: '30%', opacity: 1 }, 0); // 0ms 直接顯示
絕對定位 + 負 margin 實現垂直水平置中。
// 關閉按鈕
_obj.find('.j-dialog-close').on('click', function() {
$.jDialogRemove(id, options.close);
});
// 確定/取消/自訂按鈕
_obj.find('.j-dialog-ok').on('click', function() {
if (!options.ok()) $.jDialogRemove(id, options.close);
});
// ... 類似
// 移除函式
$.jDialogRemove = function(id, callback) {
if ($.inArray(id, jDialogId) != -1) {
jDialogId.splice($.inArray(id, jDialogId), 1);
$('#j-dialog-' + id).animate({ top: '0', opacity: 0 }, 500, function() {
$(this).remove();
if (callback) callback();
});
}
};
在 CSS 定義 .j-dialog-blue .j-dialog-header { background: #2196F3; },調用時 theme: 'blue' 即可套用。
height 或 CSS max-height + overflow:auto。jDialog 以「配置物件驅動 DOM 生成」為核心模式,代碼結構清晰,適合二次開發或學習彈出框實作原理。現代專案建議考慮 SweetAlert2、Layer 或原生 <dialog> 元素 (支援度已高)。