頁面彈窗toast和加載loading

create-at 2019-04-04

都採用單例模式,原生js實現git

兼容老版本瀏覽器內核,請將用es6語法的地方做修改es6

loading 加載

代碼: 樣式所有經過js建立style標籤注入head中,若需修改,請修改loadignStyle和loadignChildStyle 的值即刻。github

const loading = (() => {
    let loadingEle  = null
    return (status) => {
        if(!loadingEle) {
            const divEle = document.createElement('div')
            const styleEle = document.createElement('style')
            // 底部遮罩樣式
            const loadignStyle = '.loading{position: fixed;z-index: 1000;left: 0;top:0;width: 100%;height: 100%;background-color: rgba(0,0,0, .6)}'
            // loading動畫樣式
            const loadignChildStyle = '.loading div{position: absolute;width: 30px;height: 30px;top: 50%;left: 50%;margin: -15px 0 0 -15px;border: 1px solid #fff;border-right: 1px solid transparent;border-radius: 50%;animation: loading 1s linear infinite;}'
            divEle.setAttribute('class', 'loading')
            divEle.innerHTML = '<div></div>'
            styleEle.innerHTML = `${loadignStyle} ${loadignChildStyle} @keyframes loading {to {transform: rotate(360deg)}}`
            document.querySelector('head').append(styleEle)
            document.querySelector('body').append(divEle)
            loadingEle = divEle
        } else {
            // 控制loading的顯示與隱藏
            const dispalyStatus = status ? 'block': 'none';
            loadingEle.setAttribute('style', `display:${dispalyStatus}`)
        }
    }
})()

任意可調用loading函數的地方調用即刻;顯示傳入參數true,不顯示不傳參數或傳false。web

toast 彈窗

const toast = (() => {
    let once = null
    let clearTime
    return (text, time) => {
        if(!time || time<1000 ) time = 1500
        const updata = () => {
            once.innerHTML = text || ''
            once.setAttribute('style', 'position: fixed;left: 50%;z-index: 9000;max-width: 300px;padding: 5px 12px;-webkit-transform: translateX(-50%);text-align: center;border-radius: 4px;font-size: 14px;color: #fff;background-color: rgba(0,0,0,0.6);')
            clearTime = setTimeout(() => {
                once.setAttribute('style', 'display:none')
                clearTimeout(clearTime)
            }, time);
        }
        if(!once) {
            const bodyEle = document.querySelector('body')
            const div = document.createElement('div');
            bodyEle.appendChild(div)
            once = div
            updata()
        } else {
            updata()
        }
    }
})()

參數:text(彈窗文本) time(顯示時常) 時間默認或小於1000時設置爲1500毫秒瀏覽器

任意可調用的地方調用 toast 方法便可app

歡迎交流 Github
相關文章
相關標籤/搜索