美文网首页Web前端应用实例
原生JS实现Web弹出层Toast

原生JS实现Web弹出层Toast

作者: 微语博客 | 来源:发表于2021-12-02 16:01 被阅读0次

网页弹出框是一个比较常见的应用,比如在用户操作界面时弹出提醒框或者加载框,可以给用户提示一些信息。浏览器的alert()弹出警告框会中断用户操作,显得不够友好。我们可以使用原生JS写一个弹出框,类似Android的Toast组件。

先分析一下实现思路:

  • 先确定弹出框的样式,写出CSS代码。
  • 动态创建元素、设置元素样式。
  • 控制元素显示与隐藏。

写出CSS代码

根据想要实现的效果,比如边框背景字体图标等,这里写一个简单的CSS样式代码

#toast{
    position: absolute;
    display: none;
    left: 50%;
    top: 50%;
    z-index: 9999;
    margin: auto;
    padding: 16px 8px;
    transform: translate(-50%,-50%);
    min-width: 120px;
    height: 25px;
    line-height: 40px;
    border-radius: 5px;
    text-align: center;
    color: #fff;
    background-color: rgba(0,0,0,0.5);
}

如果想先知道上面的CSS样式什么样子,可以将选择器加入到一个div中演示,并将display改为block。

封装组件对象

后面创建元素和控制元素的事情都是由JS完成的,可以封装成对象,再将需要做的事情写成函数。

var toast = {}

创建了一个空对象,后面根据需求添加属性和方法。

因为需要控制显示和隐藏,所以使用setTimeout特别合适。初步设定两个需求,一是同一时间只弹出一个框,二是自动关闭,以下代码设置了三个方法,一个属性。

var toast = {
    hideTimeout : null,
    init : function(){},
    show : function(){},
    hide : function(){}
}

后面分别写出上面方法的实现代码

  • init 初始化
function () {
    var toastNode = document.createElement('div');
    toastNode.innerHTML = '<span class="text">默认提示</span>';//设置HTML模板,可以根据需求设计
    toastNode.id = 'toast';//设置id,一个页面有且仅有一个toast
    toastNode.setAttribute('class','toast');// 设置类名,如果有必要的话
    toastNode.style.display = 'none';//设置隐藏,默认隐藏
    document.body.appendChild(toastNode);//添加到body下面
}

初始化代码动态创建了一个隐藏的toast窗口,设置了一些属性

  • show 显示toast
function (text){
    if(this.hideTimeout){//判断当前是否有弹出框,有的话先关闭当前
        clearTimeout(this.hideTimeOut);
        this.hideTimeOut = null;
    }
    if(!text){//判断传入提示文本是否为空,是的话返回
        console.log('text为空');
        return;
    }
    var toastNode = document.getElementById('toast');
    if (!toastNode) {//判断toast是否初始化
        console.log('未初始化');
        return;
    }
    var toastText = toastNode.querySelector('.text');
    toastText.innerHTML = text || '';//找到toast设置显示文本
    toastNode.style.display = 'block';//设置toast为显示状态
    this.hideTimeout = setTimeout(function(){//timeout设置多久后隐藏
        toastNode.style.display = 'none';
        toast.hideTimeout = null;
    },2000);
}

上面代码有些长,但是逻辑都特别清晰,先判断toast一些状态,然后显示再隐藏。

  • hide 隐藏并移除toast
function (){
    if(this.hideTimeout){//如果当前存在toast,就关闭当前toast
        clearTimeout(this.hideTimeOut);
        this.hideTimeOut = null;
    }
    var toastNode = document.getElementById('toast');
    if (toastNode) {
        toastNode.style.display = 'none';//移除toastDOM
        document.body.removeChild(toastNode);
    }
}

隐藏并移除toast,建议把这部分放在setTimeout中,如果刚初始化就会隐藏移除的话,toast不会弹出来。

完整toast示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #toast{
            position: absolute;
            display: none;
            left: 50%;
            top: 50%;
            z-index: 9999;
            margin: auto;
            padding: 16px 8px;
            transform: translate(-50%,-50%);
            min-width: 120px;
            min-height: 25px;
            line-height: 25px;
            border-radius: 5px;
            text-align: center;
            color: #fff;
            background-color: rgba(0,0,0,0.5);
        }
        div{
            text-align: center;
        }
    </style>
</head>
<body>
    <div><button onclick="myFun()">点我弹出toast</button></div>
    <script>
        var toast = {
                hideTimeout : null,
                init : function () {
                            var toastNode = document.createElement('div');
                            toastNode.innerHTML = '<span class="text">默认提示</span>';//设置HTML模板,可以根据需求设计
                            toastNode.id = 'toast';//设置id,一个页面有且仅有一个toast
                            toastNode.setAttribute('class','toast');// 设置类名,如果有必要的话
                            toastNode.style.display = 'none';//设置隐藏,默认隐藏
                            document.body.appendChild(toastNode);//添加到body下面
                        },
                show : function (text){
                            if(this.hideTimeout){//判断当前是否有弹出框,有的话先关闭当前
                                clearTimeout(this.hideTimeOut);
                                this.hideTimeOut = null;
                            }
                            if(!text){//判断传入提示文本是否为空,是的话返回
                                console.log('text为空');
                                return;
                            }
                            var toastNode = document.getElementById('toast');
                            if (!toastNode) {//判断toast是否初始化
                                console.log('未初始化');
                                return;
                            }
                            var toastText = toastNode.querySelector('.text');
                            toastText.innerHTML = text || '';//找到toast设置显示文本
                            toastNode.style.display = 'block';//设置toast为显示状态
                            this.hideTimeout = setTimeout(function(){//timeout设置多久后隐藏
                                toastNode.style.display = 'none';
                                toast.hideTimeout = null;
                            },2000);
                        },
                hide : function (){
                            if(this.hideTimeout){//如果当前存在toast,就关闭当前toast
                                clearTimeout(this.hideTimeOut);
                                this.hideTimeOut = null;
                            }
                            var toastNode = document.getElementById('toast');
                            if (toastNode) {
                                toastNode.style.display = 'none';//移除toastDOM
                                document.body.removeChild(toastNode);
                            }
                        }
            }

        function myFun(){
            toast.init();
            toast.show("这是一条提示消息");
            setTimeout(toast.hide,2000);
        }
    </script>
    
</body>
</html>

条条大路通罗马,通往广场的路也不止一条。实现一个功能往往会有多种方法,这里只是给大家一个参考思路,很多地方还需要优化,发现不足欢迎指出。

相关文章

网友评论

    本文标题:原生JS实现Web弹出层Toast

    本文链接:https://www.haomeiwen.com/subject/uxoyxrtx.html