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

♫涵菲 阅读 2

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

现在我的写法是这样的:

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

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

我来解答 赞 0 收藏
二维码
手机扫码查看
1 条解答
长孙静依
懒人方案来了,用个队列管理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