如何使用SweetAlert打开新弹窗时不关闭旧弹窗 实现多弹窗共存效果
问题核心原因
SweetAlert2 默认采用单例设计,同一时间仅保留一个弹窗实例,新弹窗触发时会自动销毁旧实例,这是它默认无法实现多弹窗共存的根本原因。
解决方案
你可以通过关闭全局遮罩、动态计算弹窗偏移量的方式实现和iziToast一致的堆叠效果,完整可运行代码如下:
JS代码
const swalToast = Swal.mixin({ toast: true, iconColor: "white", customClass: { popup: "colored-toast" }, showConfirmButton: false, timerProgressBar: true, backdrop: false, // 必须关闭全局遮罩,避免遮挡下层弹窗 didOpen: (toast) => { // 统计已存在的同类型弹窗总高度,设置偏移量避免重叠 const existToasts = document.querySelectorAll('.colored-toast'); let bottomOffset = 0; existToasts.forEach(item => { bottomOffset += item.offsetHeight + 10; // 10为两个弹窗之间的间距,可自行调整 }); toast.style.bottom = `${bottomOffset}px`; } }); // 测试代码 swalToast.fire({ title: "One", position: "bottom", timer: 5000, icon: "info", }); setTimeout(() => { swalToast.fire({ title: "Two", position: "bottom", timer: 1500, icon: "info", }); }, 2000);
配套CSS代码
.colored-toast { position: fixed !important; z-index: 9999 !important; margin: 0 !important; } /* 对应info类型toast的样式,其他类型可按需补充 */ .colored-toast.swal2-icon-info { background-color: #3fc3ee; color: #fff; }
如果需要弹窗从顶部堆叠,只需要把didOpen回调里的bottom替换为top即可。
内容的提问来源于stack exchange,提问作者Fakhamatia
相关产品推荐
相关产品推荐

