示例网址:
https://50projects50days.com/projects/toast-notification/
http://50projects.tc.cluski.top/50projects50days/toast-notification/
效果:

思路:
右下角有一个容器使用position: fixed,定位在画面的右下角。按下按钮会生成一个新的<div>,插入到右下角的容器之中。并在3s之后删除掉:
const button = document.getElementById('button')
const toasts = document.getElementById('toasts')
const messages = [
'Message One',
'Message Two',
'Message Three',
'Message Four',
]
const types = ['info', 'success', 'error']
button.addEventListener('click', () => createNotification())
function createNotification(message = null, type = null) {
const notif = document.createElement('div')
notif.classList.add('toast')
notif.classList.add(type ? type : getRandomType())
notif.innerText = message ? message : getRandomMessage()
toasts.appendChild(notif)
setTimeout(() => {
notif.remove()
}, 3000)
}
function getRandomMessage() {
return messages[Math.floor(Math.random() * messages.length)]
}
function getRandomType() {
return types[Math.floor(Math.random() * types.length)]
}
右下角的容器采用flex布局:
#toasts {
display: flex;
justify-content: center;
/*x轴方向,靠右排布*/
align-items: flex-end;
}
评论区