Bootstrap 5 的 Toast 组件需手动初始化并触发显示,不自带全局管理逻辑;可通过封装 showToast 函数实现轻量级非阻断式消息通知,并支持类型、延迟、堆叠等定制化功能。

Bootstrap 5 内置了 Toast 组件,适合做轻量级、非阻断式的全局消息通知(如成功提示、操作反馈)。它默认不自动显示,需手动触发,也不自带全局管理逻辑,所以“全局消息通知弹窗”需要你稍作封装——但并不复杂。
1. 基础结构:先写一个可复用的 toast 模板
在页面底部(</body> 前)放一个隐藏的 toast 容器,所有通知都动态插入这里:
<div id="toast-container" class="position-fixed top-0 end-0 p-3" style="z-index: 1090;">
<div id="global-toast" class="toast align-items-center text-white bg-primary border-0" role="alert" aria-live="assertive" aria-atomic="true">
<div class="d-flex">
<div class="toast-body">
操作已成功!
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
</div>
</div>
</div>
注意点:
-
position-fixed+top-0 end-0让它固定在右上角 -
z-index: 1090高于 Bootstrap 的 modal(1050),避免被遮挡 -
aria-live="assertive"保证屏幕阅读器能及时读出内容 - 不要给
#global-toast设data-bs-autohide="true"—— 我们要自己控制显隐和时长
2. 封装一个全局通知函数(JavaScript)
用原生 JS 或 Bootstrap 的 Toast 实例 API 控制行为。推荐使用后者,更稳定:
立即学习“前端免费学习笔记(深入)”;
function showToast(message, options = {}) {
const { type = 'primary', delay = 3000, dismissible = true } = options;
const toastEl = document.getElementById('global-toast');
const toastBody = toastEl.querySelector('.toast-body');
const closeBtn = toastEl.querySelector('.btn-close');
// 更新内容和样式
toastBody.textContent = message;
toastEl.className = `toast align-items-center text-white bg-${type} border-0`;
// 是否显示关闭按钮
if (dismissible) {
closeBtn.style.display = 'block';
} else {
closeBtn.style.display = 'none';
}
// 创建并显示
const toast = new bootstrap.Toast(toastEl, {
autohide: true,
delay: delay
});
toast.show();
}
调用示例:
showToast('保存成功!', { type: 'success', delay: 2500 });
支持的 type:success / info / warning / danger / primary(对应 Bootstrap 背景色类)
3. 支持多条消息队列(进阶)
如果用户快速触发多次通知,直接覆盖会丢失信息。可改用「动态创建 + 插入」方式,每条 toast 独立存在:
<code>function showToastQueue(message, options = {}) {
const { type = 'primary', delay = 3000 } = options;
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = `toast align-items-center text-white bg-${type} border-0`;
toast.setAttribute('role', 'alert');
toast.setAttribute('aria-live', 'assertive');
toast.setAttribute('aria-atomic', 'true');
toast.innerHTML = `
<div class="d-flex">
<div class="toast-body">${message}</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
</div>
`;
container.appendChild(toast);
const bsToast = new bootstrap.Toast(toast, { delay });
bsToast.show();
// 自动移除 DOM(避免堆积)
toast.addEventListener('hidden.bs.toast', () => {
toast.remove();
});
}
这样每次调用都会生成新 toast,从上到下依次堆叠,互不影响。
4. 样式微调(可选)
默认 toast 宽度较窄,可加自定义 CSS 提升体验:
#toast-container .toast {
min-width: 320px;
max-width: 480px;
margin-bottom: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
如果希望从右上角「滑入」,确保 Bootstrap 的 toast CSS 已加载(v5.3+ 默认启用动画),无需额外写 transition。
不复杂但容易忽略:务必确认已引入 Bootstrap 5 的 JS(含 toast 插件)和 CSS,并且没有重复初始化或冲突的 jQuery 版本(Bootstrap 5 不依赖 jQuery)。



















