一个简单的提示框

CSS:

/*提示框*/
.dialog-box {
    max-width: 300px;
    background-color: #000;
    opacity: 0.8;
    color: #fff;
    padding: 25px 35px;
    position: fixed;
    top: 40%;
    left: 50%;
    transform: translate(-50%);
    border-radius: 6px;
    display: none;
    z-index: 9999;
    font-size: 16px;
    text-align: center;
}

JS / JQ :

//原生JS:
function showTip(str, t, fun) {
    t = t || 1500;
    var dom = document.createElement("p");
    dom.setAttribute('class', 'dialog-box');
    document.body.appendChild(dom);
    var _dialog = document.querySelector('.dialog-box')
    _dialog.style.display="block";
    _dialog.innerHTML = str;
    setTimeout(function () {
        _dialog.style.display="none";
        _dialog.parentNode.removeChild(_dialog);
        if (fun) {fun();}
    }, t);
}

//或

//用JQ:
function showTip(str, t, fun) {
    t = t || 1500;
    $(document.body).append("<p class='dialog-box'></p>");
    var $dialog = $(".dialog-box");
    $dialog.fadeIn().html(str);
    setTimeout(function () {
        $dialog.fadeOut();
        $dialog.remove();
        if (fun) {fun();}
    }, t);
}



调用:

showTip('这是一个提示框', 2000, function () {
    console.log('弹框2秒消失,并执行回调')
});

效果如下:

这里写图片描述


注:时间和回调参数非必填~

posted @ 2022-07-20 18:16  猫老板的豆  阅读(24)  评论(0编辑  收藏  举报