刪除操作不可逆,必須要求用戶二次確認。最簡單的是原生 confirm(),但樣式固定、無法自義、阻塞主執行緒。本文提供原生方案快速上手,並進階實作可複用、無障礙、支援 Promise 的自訂確認對話框元件。
<a href="/delete/123" onclick="return confirmDelete()">刪除</a>
<script>
function confirmDelete() {
return confirm('確定要刪除此項目嗎?此操作不可恢復。');
}
</script>
優點:無依賴、阻塞執行 (同步)、瀏覽器原生支援。
缺點:樣式不可控、無法包含 HTML、阻塞主執行緒、移動端體驗差、無法符合品牌設計規範。
<div id="confirm-modal" class="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title" hidden>
<div class="modal-overlay" tabindex="-1"></div>
<div class="modal-content">
<h3 id="modal-title">確認刪除</h3>
<p id="modal-message">確定要刪除嗎?</p>
<div class="modal-actions">
<button type="button" class="btn btn-cancel" data-action="cancel">取消</button>
<button type="button" class="btn btn-confirm" data-action="confirm">刪除</button>
</div>
</div>
</div>
.modal { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center; }
.modal[hidden] { display: none; }
.modal-overlay { position: absolute; inset: 0; background: rgba(0,0,0,0.5); }
.modal-content { position: relative; background: white; border-radius: 8px; padding: 24px; min-width: 320px; max-width: 90vw; box-shadow: 0 10px 30px rgba(0,0,0,0.3); animation: modal-in 0.2s ease; }
@keyframes modal-in { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }
.modal-actions { display: flex; justify-content: flex-end; gap: 12px; margin-top: 16px; }
.btn { padding: 8px 16px; border-radius: 4px; border: none; cursor: pointer; font-size: 14px; }
.btn-cancel { background: #e0e0e0; color: #333; }
.btn-cancel:focus, .btn-confirm:focus { outline: 2px solid #007bff; outline-offset: 2px; }
.btn-confirm { background: #dc3545; color: white; }
/**
* 顯示確認對話框
* @param {string} message - 提示訊息
* @param {string} [title='確認操作'] - 標題
* @param {Object} [options] - 選項
* @returns {Promise} true=確認, false=取消
*/
function confirmDialog(message, title = '確認操作', options = {}) {
return new Promise((resolve) => {
const modal = document.getElementById('confirm-modal');
const messageEl = document.getElementById('modal-message');
const titleEl = document.getElementById('modal-title');
const confirmBtn = modal.querySelector('[data-action="confirm"]');
const cancelBtn = modal.querySelector('[data-action="cancel"]');
const overlay = modal.querySelector('.modal-overlay');
// 設定內容
titleEl.textContent = title;
messageEl.textContent = message;
confirmBtn.textContent = options.confirmText || '確定';
cancelBtn.textContent = options.cancelText || '取消';
confirmBtn.className = 'btn btn-confirm ' + (options.confirmClass || '');
cancelBtn.className = 'btn btn-cancel ' + (options.cancelClass || '');
// 焦點管理:記錄觸發元素,關閉後恢復焦點
const triggerEl = document.activeElement;
function close(result) {
modal.hidden = true;
document.body.style.overflow = '';
// 恢復焦點
if (triggerEl && triggerEl.focus) triggerEl.focus();
// 移除事件監聽 (防止重複綁定)
cleanup();
resolve(result);
}
function onAction(e) {
const action = e.target.closest('[data-action]')?.dataset.action;
if (action === 'confirm') close(true);
else if (action === 'cancel') close(false);
}
function onKeyDown(e) {
if (e.key === 'Escape') close(false);
// Tab 焦點陷阱 (簡易版)
if (e.key === 'Tab') {
const focusable = modal.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
}
}
function cleanup() {
modal.removeEventListener('click', onAction);
document.removeEventListener('keydown', onKeyDown);
overlay.removeEventListener('click', () => close(false));
}
// 綁定事件
modal.addEventListener('click', onAction);
document.addEventListener('keydown', onKeyDown);
overlay.addEventListener('click', () => close(false)); // 點遮罩取消
// 顯示
modal.hidden = false;
document.body.style.overflow = 'hidden'; // 防止背景捲動
// 聚焦確認按鈕 (危險操作預設聚焦取消更安全,視產品策略)
cancelBtn.focus();
});
}
// 使用範例:綁定刪除按鈕 (事件委派)
document.body.addEventListener('click', async function (e) {
const btn = e.target.closest('[data-delete-id]');
if (!btn) return;
e.preventDefault(); // 阻止 預設跳轉
const id = btn.dataset.deleteId;
const confirmed = await confirmDialog(
`確定要刪除項目 #${id} 嗎?此操作不可恢復。`,
'刪除確認',
{ confirmText: '刪除', confirmClass: 'btn-danger' }
);
if (confirmed) {
// 發送刪除請求
fetch('/api/items/' + id, { method: 'DELETE' })
.then(r => r.json())
.then(res => {
if (res.success) {
btn.closest('tr')?.remove(); // 移除列表行
showToast('刪除成功');
} else {
alert('刪除失敗: ' + res.message);
}
});
}
});
| 庫 | 體積 | 特點 | 適用場景 |
|---|---|---|---|
| SweetAlert2 | ~40 KB | 功能最豐富、動畫優美、Promise、TypeScript、SSR 友善 | 企業級專案、需豐富互動 |
| Bootbox.js | ~15 KB | Bootstrap 風格、API 簡單、依賴 Bootstrap/jQuery | Bootstrap 專案快速整合 |
| Modaal | ~8 KB | 無障礙優先、無依賴、支援圖片/視頻/iframe | 輕量、無障礙要求高 |
| 原生 | 0 KB | HTML 原生標籤、支援 showModal()、表單關閉、瀏覽器支援度較新 | 現代專案、可接受 Polyfill |