基于原生JavaScript的loading效果组件


/**
 * Loading
 * 用于创建一个加载框
 */
class Loading{
    title = "";
    dom = "";

    body = document.body;
    constructor(title="加载中..."){
        this.title = title;
        this.dom = this.createLoadDom()
    }
    createLoadDom(){
        // 加载窗口容器
        let box = document.createElement("div")
        box.style.position = "fixed"
        box.style.display = "flex"
        box.style.flexDirection = "column"
        box.style.justifyContent = "center"
        box.style.alignItems = "center"
        box.style.background = "rgba(0,0,0,1)"
        box.style.width = "100vw"
        box.style.height = "100vh"
        box.style.top = "0px"
        box.style.zIndex = "2000"
        box.style.display = "None"
        // 加载窗口提示字符
        let text = document.createElement("div")
        text.innerText = this.title
        text.style.fontSize = "1.4em"
        text.style.color = "#fff"
        text.style.marginBottom = "0.4em"
        // 加载动画
        document.styleSheets[0].insertRule(
            `@keyframes n_line_gd {
                0% {left: -20%;}
                20% {left: 0%;} 
                40% {left: 50%;} 
                50% {left: 100%;}
                60% {left: 50%;} 
                80% {left: 0%;} 
                100% {left: -20%;} 
            }
            `,
            0
        );

        let l_line = document.createElement("div")
        l_line.style.width = "20%"
        l_line.style.height = "22px"
        l_line.style.border = "1px solid #fff"
        l_line.style.padding = "1px 1px 1px 1px"
        l_line.style.overflow = "hidden"

        let n_line = document.createElement("div")
        n_line.style.width = "20%"
        n_line.style.height = "22px"
        n_line.style.backgroundColor = "#fff"
        n_line.style.position = "relative"
        n_line.style.left = "-20px"
        n_line.style.animation = "n_line_gd 2s linear infinite"

        l_line.appendChild(n_line)

        box.appendChild(text)
        box.appendChild(l_line)
        this.body.appendChild(box)
        return box
    }
    play(callback=()=>{},...args){
        this.dom.style.display = "flex"
        setTimeout(()=>{
            callback(...args)
        },2)

    }
    end(){
        this.dom.style.display = "None"
    }
}

let ld = new Loading()
ld.play(funcation) // 启动加载效果
ld.end() // 关闭加载效果

声明:一代明君的小屋|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - 基于原生JavaScript的loading效果组件


欢迎来到我的小屋