侧边栏壁纸
  • 累计撰写 57 篇文章
  • 累计创建 23 个标签
  • 累计收到 4 条评论

50projects50days知识点-27-toast-notification

cluski
2023-03-29 / 0 评论 / 0 点赞 / 152 阅读 / 223 字
温馨提示:
本文最后更新于 2023-03-29,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

    示例网址:

    https://50projects50days.com/projects/toast-notification/
    http://50projects.tc.cluski.top/50projects50days/toast-notification/

    效果:

    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;
    }
    
    0

    评论区