JS全局弹框插件

原生 JS 写一个自己的全局弹框组件,灵活的传递文本内容和icon的灵活显示隐藏。

1、V1版本

// 接受一个 id 或者类选择器 作为复制源, 必须是 input 或者 textarea

function _copy(el){

    if (el.length !== 0 && el.indexOf('#') !== -1) {

        el = el.split('#')[1]

        document.getElementById(el).select()

    } else if(el.length !== 0 && el.indexOf('.') !== -1) {

        document.querySelector(el).select()

    }

    document.execCommand('copy')

    _dialog()

}

// 接受一个自定义提示信息,默认 复制成功

function _dialog(msg = '复制成功') {

    const div = document.createElement('div')

    div.id = 'rnl-dialog'

    div.innerHTML = msg

    document.documentElement.appendChild(div)

    const dialog = document.getElementById('rnl-dialog')

    dialog.style = `position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%); background: rgba(0, 0,0,.5); padding: 2px 5px;font-size: 16px; border-radius: 3px;color: #fff;z-index: 9999;`

    setTimeout(()=>{

        div.remove()

    },500)

}  

2、V2版本

// 调用方法:rnl.msg(内容,options)  options:可选参数,object类型,有time,icon

; var RnlMessage = (function () {

    function RNL() {

        this.timeId = null

        this.init = init()

    }

    function init() {

        const str = `

     <div class="rnl-dialog"

      style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 6px 10px; background: rgba(0, 0,0,.5); border-radius: 8px; transition: all .3s; display: none; z-index: 20230526;">

        <div style="display: flex; flex-direction: column; align-items: center;">

            <img id="rnl-dialog-icon" width: 30px;height: 26px;" src="https://cdn.leishennb.icu/1.png">

            <div id="rnl-content" style="color: #fff;"></div>

        </div>

     </div>

     `

        const child = document.createElement('div')

        child.innerHTML = str

        document.body.appendChild(child)

    }

    RNL.prototype.msg = function (content, options) {

        const icon = document.getElementById('rnl-dialog-icon')

        if (options?.icon === false) {

            icon.style.display = 'none'

        }

        const rnlDialog = document.querySelector('.rnl-dialog')

        rnlDialog.style.display = 'block'

        var times = null

        times = options !== undefined && options.time ? options.time - 0 : 2000;

        this.content(content)

        clearTimeout(this.timeId)

        this.timeId = setTimeout(() => {

            rnlDialog.style.display = 'none'

        }, times)

    }

    RNL.prototype.content = function (content) {

        if (content) {

            document.getElementById('rnl-content').innerHTML = content

        }

    }

    return new RNL()

}());

 

点此发表评论