天天看点

一个简单的js消息提示框

调用完成后的消息提示框

之前因为写一些验证,会在调用成功或者失败后用到一些消息提示框,但找了很多了没找到比较合适的,对于一些框架中的组件感觉用着也不是很方便,于是自己用js写了一个简单的提示框,代码如下:

function showMessage(message,type,time) {
        let str = ''
        switch (type) {
            case 'success':
                str = '<div class="success-message" style="width: 300px;height: 40px;text-align: center;background-color:#daf5eb;;color: rgba(59,128,58,0.7);position: fixed;left: 43%;top: 10%;line-height: 40px;border-radius: 5px;z-index: 9999">\n' +
                    '    <span class="mes-text">'+message+'</span></div>'
                break;
            case 'error':
                str = '<div class="error-message" style="width: 300px;height: 40px;text-align: center;background-color: #f5f0e5;color: rgba(238,99,99,0.8);position: fixed;left: 43%;top: 10%;line-height: 40px;border-radius: 5px;;z-index: 9999">\n' +
                    '    <span class="mes-text">'+message+'</span></div>'
        }
        $('body').append(str)
        setTimeout(function () {
            $('.'+type+'-message').remove()
        },time)
    }
           

以上就是写好的js代码,我们通过下面的方法调用提示框:

showMessage('添加成功','success',1000)
           

这样就可以完成一次提示框的调用,其中第一个参数是提示框的内容,第二个参数是这里是success,代表成功的提示框,这里只只是success或者error,success提示框为淡绿色,error为淡红色,第三个参数是提示框消失时间,这里1000表示1000ms,也就是一秒,传入这三个参数就可以完成提示框的调用啦,如需要更多类型提示框,可以在case里继续添加,希望你们能喜欢,有可以优化的地方也可以提出宝贵的意见