全局提示组件怎么在页面任意位置触发?

♫涵菲 阅读 48

我用的是原生 JS 写了个简单的全局提示(Toast),但每次都要手动 append 到 body 里,而且多个提示会堆叠在一起。有没有更优雅的方式?比如封装成一个函数,调用时自动创建并显示?

现在我的写法是这样的:

<div id="toast" style="position: fixed; top: 20px; right: 20px; background: #333; color: white; padding: 10px; border-radius: 4px;">
  提示内容
</div>

但这样只能显示一个,新提示会覆盖旧的,而且位置固定死了,不太灵活。

我来解答 赞 8 收藏
二维码
手机扫码查看
2 条解答
百里瑞玲
问题在于你没有把Toast封装成独立组件,每次调用都需要手动处理DOM。

直接上代码:

const toast = (msg, duration = 2000) => {
const old = document.querySelector('.global-toast');
old && old.remove();

const el = document.createElement('div');
el.className = 'global-toast';
el.textContent = msg;
el.style.cssText =
position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
background: #333; color: #fff; padding: 12px 24px;
border-radius: 4px; z-index: 9999; font-size: 14px;
;
document.body.appendChild(el);

setTimeout(() => el.remove(), duration);
};

// 调用
toast('操作成功');
toast('网络错误', 3000);


这样调用一次就显示一个,新调用会自动移除旧的,不用手动管理DOM。位置改成居中了,看需求可以改top、right之类的。
点赞 2
2026-03-12 18:14
长孙静依
懒人方案来了,用个队列管理toast,自动创建销毁,还能设置显示时间:

const toastQueue = []
let isShowing = false

function showToast(msg, duration = 2000) {
toastQueue.push(msg)
if (!isShowing) processQueue()
}

function processQueue() {
if (toastQueue.length === 0) {
isShowing = false
return
}

isShowing = true
const toast = document.createElement('div')
toast.style.cssText =
position: fixed;
top: 20px;
right: 20px;
background: #333;
color: white;
padding: 10px;
border-radius: 4px;

toast.textContent = toastQueue.shift()
document.body.appendChild(toast)

setTimeout(() => {
toast.remove()
processQueue()
}, 2000)
}

// 用的时候直接 showToast('你的提示内容') 就行


这样每次调用会自动排队显示,不用手动管理dom,用完自动销毁,美滋滋。
点赞
2026-03-05 19:13