alert()弹窗美化

相信大家在写前端的时候都会遇到这样一个问题;
就是alert()和confirm()弹窗不够美观;
那么怎么办呢?
有没有什么可以用来替换alert()和confirm()弹窗?
这个肯定是有的;
给大家介绍一个JS自定义函数jqueryAlert();
冯奎博客
上图就是jqueryAlert()弹窗的样式;
文件下载地址    链接:https://pan.baidu.com/s/1QBDezs7QqXfFDubtQmOJvw 密码:nll8
来说一下这个函数;
JS中加载同名CSS:

function loadStyle(href)            //加载css
{
    $("head")[0].appendChild($("<link />", {
        href: href,
        rel: "stylesheet",
        type: "text/css",
        charset: "utf-8"
    })[0]);
}
var path = $("script").eq(-1).attr("src").replace(/[^\/]+$/,"");    //用户页面与插件目录的相对路径
loadStyle(path+"alert.css");

jqueryAlert弹窗函数:

var zIndex = 1000;
var jqueryAlert = function(opts){
    // 设置默认参数
    var opt = {
        'style'        : 'wap', //移动端和PC端
        'title'        : '',    //标题
        'icon'         : '',
        'content'      : '',    //内容
        'contentTextAlign' : 'center', //内容对齐方式
        'width'        : 'auto', //宽度
        'height'       : 'auto', //高度
        'minWidth'     : '0', //最小宽度
        "className"    : '', //添加类名
        'position'     : 'fixed', //定位方式
        'animateType'  : 'scale',
        'modal'        : false, //是否存在蒙层
        'isModalClose' : false, //点击蒙层是否关闭
        'bodyScroll'   : false, //是否关闭body的滚动条
        'closeTime'    : 3000, //当没有按钮时关闭时间
        "buttons"      : {}, //按钮对象</pre>
        "end"          : {}, //提示之后置操作
    }

    // 参数合并
    var option = $.extend({},opt,opts);

    var dialog = {

    }

    dialog.time = 450;//动画关闭时间
    dialog.init = function(){
        dialog.framework();
    }

    // 事件处理
    var isHaveTouch = "ontouchend" in document ? true : false;
    if(isHaveTouch){
        dialog.event = 'touchstart';
    }else{
        dialog.event = 'click';
    }

    var $modal = $("<div class='alert-modal'>")
    var $container = $("<div class='alert-container animated'>");
    var $title = $("<div class='alert-title'>"+option.title+"</div>");
    var $content = $("<div class='alert-content'>");
    var $buttonBox = $("<div class='alert-btn-box'>");
    var $closeBtn = $("<div class='alert-btn-close'>×</div>");

    if(option.content[0].nodeType == 1){
        var $newContent = option.content.clone();
        $content.append($newContent)
    }else{
        $content.html(option.content);
    }

    dialog.framework = function(){

        dialog.buttons = [];
        for(var key in option.buttons){
            dialog.buttons.push(key);
        }
        dialog.buttonsLength = dialog.buttons.length;

        $container.append($title)
                  .append($content);

        if(option.style == 'pc'){
            $container.append($closeBtn).addClass('pcAlert');
        }

        if(option.modal || option.modal == 'true'){
            $('body').append($modal)
            option.bodyScroll && $('body').css('overflow','hidden');
        }
        $('body').append($container)

        // 设置内容的对齐方式
        $content.css({
            'text-align' : option.contentTextAlign
        })

        if(parseInt(option.minWidth) > parseInt($container.css('width'))){
            option.width = option.minWidth;
        }

        $modal.css('position',option.position);
        $modal.css('z-index',zIndex);

        ++zIndex;

        if(option.position == 'fixed'){
            $container.css({
                'position' : option.position,
                'left'     : '50%',
                'top'      : '50%',
                'z-index'  : zIndex,
            })
        }
        if(option.position == 'absolute'){
            $container.css({
                'position' : option.position,
                'left'     : $(window).width()/2,
                'top'      : $(window).height()/2 + $(window).scrollTop(),
                'z-index'  : zIndex,
            })
        }

        $container.css('width',option.width);
        $container.css('height',option.height);

        if(option.width == 'auto'){
            $container.css('width',$container[0].clientWidth + 10);
        }

        if(parseInt($(window).height()) <=  parseInt($container.css('height'))){
            $container.css('height',$(window).height());
        }

        // 设置class
        (!!option.className) && $container.addClass(option.className);

        // 设置button内容
        for(var key in option.buttons){

            var $button = $("<p class='alert-btn-p'>"+ key +"</p>");
            if(option.style != 'pc'){
                $button.css({
                    'width' : Math.floor(($container[0].clientWidth) / dialog.buttonsLength),
                })
            }
            //绑定点击后的事件
            $button.bind(dialog.event,option.buttons[key]);
            $buttonBox.append($button);

        }

        if(dialog.buttonsLength > 0){
            $container.append($buttonBox);
            $content.css('padding-bottom','46px');
        }

        if(option.title != ''){
            $content.css('padding-top','42px');
        }

        if(dialog.buttonsLength <= 0 && option.title == ''){
            $container.addClass('alert-container-black');
            if(!!option.icon){
                $content.css({
                    'padding-top' : '45px',
                    'background'  : 'url('+option.icon+') no-repeat center 5px',
                    'background-size' : 'auto 40px'
                })
            }
        }

         // 设置定位
        $container.css({
            'margin-left' : -parseInt($container.css('width'))/2,
            'margin-top' : -parseInt($container.css('height'))/2,
        });
        if(option.animateType == 'scale'){
            $container.addClass('bounceIn');
        }
        if(option.animateType == 'linear'){
            $container.addClass('linearTop');
        }
        isSelfClose();
    };

    // 判断是否满足自动关闭的条件
    function isSelfClose(){
        if(dialog.buttonsLength <= 0 && option.style != 'pc'){
            setTimeout(function(){
                $container.fadeOut(300);
                $modal.fadeOut(300);
                option.bodyScroll && $('body').css('overflow','auto');

                if (typeof option.end === "function") {
                    option.end();
                };

            },option.closeTime)
        }
    }

    dialog.toggleAnimate = function(){
        if(option.animateType == 'scale'){
            return $container.removeClass('bounceIn').addClass('bounceOut');
        }else if(option.animateType == 'linear'){
            return $container.removeClass('linearTop').addClass('linearBottom');
        }else{
            return $container;
        }
    }

    dialog.close = function(){
        dialog.toggleAnimate().fadeOut(dialog.time);
        $modal.fadeOut(dialog.time);
        option.bodyScroll && $('body').css('overflow','auto');
    };

    option.style == 'pc' && $closeBtn.bind(dialog.event,dialog.close);
    option.isModalClose && $modal.bind(dialog.event,dialog.close);

    dialog.destroy = function(){
        dialog.toggleAnimate().fadeOut(dialog.time);
        setTimeout(function(){
            $container.remove();
            $modal.remove();
            option.bodyScroll && $('body').css('overflow','auto');
        },dialog.time)
    }
    dialog.show = function(){
        $modal.css('z-index',zIndex);
        ++zIndex;
        $container.css({
            'z-index'  : zIndex,
        })
        if(option.animateType == 'scale'){
            $container.fadeIn().removeClass('bounceOut').addClass('bounceIn');
        }else if(option.animateType == 'linear'){
            $container.fadeIn().removeClass('linearBottom').addClass('linearTop');
        }else{
            $container.fadeIn()
        }
        if(option.position == 'absolute'){
            $container.css({
                'top'      : $(window).height()/2 + $(window).scrollTop(),
            })
        }
        $modal.fadeIn();
        option.bodyScroll && option.modal && $('body').css('overflow','hidden');
        isSelfClose();
    }
    dialog.init();
    return dialog;
}

新建一个index.html的文件;
这里介绍jqueryAlert()弹窗的几种使用方法:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <link rel="stylesheet" href="alert.css">
        <script src='jquery-1.9.0.min.js'></script>
        <script src='alert.js'></script>
        <style>html,body{ height: 100%; width:100%; } legend{ padding:0 20px; } body{ display: flex; align-items: center; justify-content: center; } fieldset{ padding:20px; display: inline-block; }</style></head>
    <body>
        <fieldset class="m20 fieldset">
            <legend>实例演示</legend>
            <button class="alert-api-button alert-btn1">默认提示</button>
            <button class="alert-api-button alert-btn11">正确提示</button>
            <button class="alert-api-button alert-btn12">错误提示</button>
            <button class="alert-api-button alert-btn13">警告提示</button>
            <button class="alert-api-button alert-btn2">按钮1</button>
            <button class="alert-api-button alert-btn3">按钮2</button>
            <button class="alert-api-button alert-btn4">不使用动画</button>
            <button class="alert-api-button alert-btn5">动画2</button>
            <button class="alert-api-button alert-btn6">捕获页</button>
            <button class="alert-api-button alert-btn7">iframe层</button>
            <button class="alert-api-button alert-btn9">pc弹层</button></fieldset>
    </body>
    <script>var M = {
}
        // 按钮一1
        $(document).delegate(".alert-btn1", 'click',
        function() {
            jqueryAlert({'content' : 'hello 程序员...','closeTime' : 2000,end:function(){
            window.location.href = "https://fengkui.net/";
        }});
        })
        // 按钮一2
        $(document).delegate(".alert-btn11", 'click',
        function() {
            if (M.dialog11) {
                return M.dialog11.show();
            }
            M.dialog11 = jqueryAlert({
                'icon': './right.png',
                'content': 'hello 程序员...',
                'closeTime': 2000,
            })
        })
        // 按钮一3
        $(document).delegate(".alert-btn12", 'click',
        function() {
            if (M.dialog12) {
                return M.dialog12.show();
            }
            M.dialog12 = jqueryAlert({
                'icon': './error.png',
                'content': 'hello 程序员...',
                'closeTime': 2000,
            })
        })
        // 按钮一4
        $(document).delegate(".alert-btn13", 'click',
        function() {
            if (M.dialog13) {
                return M.dialog13.show();
            }
            M.dialog13 = jqueryAlert({
                'icon': './warning.png',
                'content': 'hello 程序员...',
                'closeTime': 2000,
            })
        })
        // 按钮二
        $(document).delegate(".alert-btn2", 'click',
        function() {
            if (M.dialog2) {
                return M.dialog2.show();
            }
            M.dialog2 = jqueryAlert({
                'content': 'hello 程 序 员 ...',
                'modal': true,
                'buttons': {
                    '确定': function() {
                        M.dialog2.close();
                    }
                }
            })
        })
        // 按钮三
        $(document).delegate(".alert-btn3", 'click',
        function() {
            if (M.dialog3) {
                return M.dialog3.show();
            }
            M.dialog3 = jqueryAlert({
                'title': 'alertjs提示',
                'content': '欢迎使用alertjs弹层 ...',
                'modal': true,
                'buttons': {
                    '确定': function() {
                        M.dialog3.close();
                    },
                    '我不是': function() {
                        if (M.dialog31) {
                            return M.dialog31.show();
                        }
                        M.dialog31 = jqueryAlert({
                            'content': '我不是程序员...'
                        })
                    }
                }
            })
        })
        // 按钮四
        $(document).delegate(".alert-btn4", 'click',
        function() {
            if (M.dialog4) {
                return M.dialog4.show();
            }
            M.dialog4 = jqueryAlert({
                'title': 'alertjs提示',
                'content': '欢迎使用alertjs弹层 ...',
                'modal': true,
                'animateType': '',
                'buttons': {
                    '确定': function() {
                        M.dialog4.close();
                    },
                    '不使用': function() {
                        if (M.dialog41) {
                            return M.dialog41.show();
                        }
                        M.dialog41 = jqueryAlert({
                            'content': '祝您找到更好用的...'
                        })
                    }
                }
            })
        })
        var alertContent = '<div>\\
   <h3>用户注册协议</h3>\\
   <p>\\
    </p><h4>一、总则</h4>\\
    1.1  保宝网的所有权和运营权归深圳市永兴元科技有限公司所有。 <br>\\
1.2  用户在注册之前,应当仔细阅读本协议,并同意遵守本协议后方可成为注册用户。一旦注册成功,则用户与保宝网之间自动形成协议关系,用户应当受本协议的约束。用户在使用特殊的服务或产品时,应当同意接受相关协议后方能使用。  <br>\\
1.3 本协议则可由保宝网随时更新,用户应当及时关注并同意本站不承担通知义务。本站的通知、公告、声明或其它类似内容是本协议的一部分。  \\
   <p></p>\\
   <p>\\
   </p><h4>二、服务内容</h4>\\
   2.1 保宝网的具体内容由本站根据实际情况提供。 <br>\\
2.2 本站仅提供相关的网络服务,除此之外与相关网络服务有关的设备(如个人电脑、手机、及其他与接入互联网或移动网有关的装置)及所需的费用(如为接入互联网而支付的电话费及上网费、为使用移动网而支付的手机费)均应由用户自行负担。\\
   <p></p>\\
   <p>\\
    </p><h4>三、用户帐号</h4>\\
    3.1 经本站注册系统完成注册程序并通过身份认证的用户即成为正式用户,可以获得本站规定用户所应享有的一切权限;未经认证仅享有本站规定的部分会员权限。保宝网有权对会员的权限设计进行变更。 <br>\\
3.2 用户只能按照注册要求使用真实姓名,及身份证号注册。用户有义务保证密码和帐号的安全,用户利用该密码和帐号所进行的一切活动引起的任何损失或损害,由用户自行承担全部责任,本站不承担任何责任。如用户发现帐号遭到未授权的使用或发生其他任何安全问题,应立即修改帐号密码并妥善保管,如有必要,请通知本站。因黑客行为或用户的保管疏忽导致帐号非法使用,本站不承担任何责任。 \\
  </div>'
        // 按钮五
        $(document).delegate(".alert-btn5", 'click',
        function() {
            if (M.dialog5) {
                return M.dialog5.show();
            }
            M.dialog5 = jqueryAlert({
                'content': alertContent,
                'modal': true,
                'contentTextAlign': 'left',
                'width': '400px',
                'animateType': 'linear',
                'buttons': {
                    '不同意': function() {
                        M.dialog5.close();
                    },
                    '同意': function() {
                        if (M.dialog51) {
                            return M.dialog51.show();
                        }
                        M.dialog51 = jqueryAlert({
                            'content': '同意也不能注册哦...'
                        })
                    }
                }
            })
        })
        // 按钮六
        $(document).delegate(".alert-btn6", 'click',
        function() {
            if (M.dialog6) {
                return M.dialog6.show();
            }
            M.dialog6 = jqueryAlert({
                'style': 'pc',
                'title': '捕获页',
                'content': $(".fieldset"),
                'modal': true,
                'contentTextAlign': 'left',
                'width': 'auto',
                'animateType': 'linear',
                'buttons': {
                    '关闭': function() {
                        M.dialog6.close();
                    },
                }
            })
        })
        // 按钮七
        $(document).delegate(".alert-btn7", 'click',
        function() {
            if (M.dialog7) {
                return M.dialog7.show();
            }
            M.dialog7 = jqueryAlert({
                'style': 'pc',
                'title': 'iframe层',
                'content': alertContent,
                'modal': true,
                'contentTextAlign': 'left',
                'width': '300',
                'height': '200',
                'animateType': 'linear',
                'buttons': {
                    '关闭': function() {
                        M.dialog7.close();
                    },
                }
            })
        })
        // 按钮九
        $(document).delegate(".alert-btn9", 'click',
        function() {
            if (M.dialog9) {
                return M.dialog9.show();
            }
            M.dialog9 = jqueryAlert({
                'style': 'pc',
                'title': 'pc弹层',
                'content': 'PC端普通弹层呦呦呦...',
                'modal': true,
                'contentTextAlign': 'left',
                'animateType': 'scale',
                'bodyScroll': 'true',
                'buttons': {
                    '关闭': function() {
                        M.dialog9.close();
                    },
                    '去首页': function() {
                        location.href = "#";
                    }
                }
            })
        })
    </script>
</html>

下面就是这个弹窗的样式文件alert.css:

* {margin:0;padding:0;}
body {font-family:"微软雅黑"}
.alert-modal {left:0;top:0;width:100%;height:100%;background:#000;opacity:0.6;filter:alpha(opacity=60);}
.alert-container {display:inline-block;border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;-o-border-radius:5px;background:#fff;border:1px solid #f1f1f1;z-index:99999;box-sizing:border-box;overflow:hidden;}
.alert-title {font-size:16px;text-align:center;line-height:42px;color:#111;background:#fff;position:absolute;left:0;top:0;z-index:999;width:100%;text-align:center;}
.alert-content {font-size:14px;padding:15px 20px;color:#555;box-sizing:border-box;height:100%;overflow:auto;}
.alert-content-scrollbar {}
.alert-btn-box {border-top:1px solid #f1f1f1;text-align:right;position:absolute;left:0;background:#fff;bottom:0;z-index:999;width:100%;}
.alert-btn-p {display:inline-block;text-align:center;border-right:1px solid #f1f1f1;font-size:14px;line-height:35px;cursor:pointer;color:#222;box-sizing:border-box;}
.alert-btn-p:hover {background:#eee;}
.alert-btn-p:last-child {border-right:none;}
.pcAlert .alert-btn-box {padding-right:10px;border:none;}
.pcAlert .alert-btn-p {border:1px solid #f1f1f1;border-radius:3px;-webkit-border-radius:3px;-moz-border-radius:3px;-o-border-radius:3px;box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;-o-box-sizing:border-box;line-height:30px;margin:7px 0;padding:0 10px;margin-right:10px;}
.alert-btn-close {position:absolute;right:10px;top:3px;font-size:24px;cursor:pointer;z-index:1000;}
.alert-container-black {background-color:rgba(0,0,0,0.65);border:none;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#7f000000,endColorstr=#7f000000);}
.alert-container-black .alert-content {color:#fff;}
.linearTop {-webkit-animation-name:linearTop;-moz-animation-name:linearTop;-o-animation-name:linearTop;animation-name:linearTop;}
.linearBottom {-webkit-animation-name:linearBottom;-moz-animation-name:linearBottom;-o-animation-name:linearBottom;animation-name:linearBottom;}
@keyframes linearBottom {0% {-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);opacity:1;filter:alpha(opacity=100);}
100% {-webkit-transform:translate3d(0,80px,0);-moz-transform:translate3d(0,80px,0);-o-transform:translate3d(0,80px,0);transform:translate3d(0,80px,0);opacity:0;filter:alpha(opacity=0);}
}
@keyframes linearTop {0% {-webkit-transform:translate3d(0,80px,0);-moz-transform:translate3d(0,80px,0);-o-transform:translate3d(0,80px,0);transform:translate3d(0,80px,0);opacity:0;filter:alpha(opacity=0);}
100% {-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);opacity:1;filter:alpha(opacity=100);}
}
/*显示动画*/.animated.infinite {animation-iteration-count:infinite;-webkit-animation-iteration-count:infinite;-moz-animation-iteration-count:infinite;-o-animation-iteration-count:infinite;}
.animated.linearBottom,.animated.linearTop,.animated.bounceIn,.animated.bounceOut {-webkit-animation-duration:.45s;-moz-animation-duration:.45s;-o-animation-duration:.45s;animation-duration:.45s;}
@keyframes bounceIn {0%,20%,40%,60%,80%,100% {-webkit-animation-timing-function:cubic-bezier(0.215,0.610,0.355,1.000);-moz-animation-timing-function:cubic-bezier(0.215,0.610,0.355,1.000);-o-animation-timing-function:cubic-bezier(0.215,0.610,0.355,1.000);animation-timing-function:cubic-bezier(0.215,0.610,0.355,1.000);}
0% {opacity:0;filter:alpha(opacity=0);-webkit-transform:scale3d(.3,.3,.3);-moz-transform:scale3d(.3,.3,.3);-o-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3);}
100% {opacity:1;filter:alpha(opacity=100);-webkit-transform:scale3d(1,1,1);-moz-transform:scale3d(1,1,1);-o-transform:scale3d(1,1,1);transform:scale3d(1,1,1);}
}
.bounceIn {-webkit-animation-name:bounceIn;-moz-animation-name:bounceIn;-o-animation-name:bounceIn;animation-name:bounceIn;}
@keyframes bounceOut {20% {-webkit-transform:scale3d(1.2,1.2,1.2);-moz-transform:scale3d(1.2,1.2,1.2);-o-transform:scale3d(1.2,1.2,1.2);transform:scale3d(1.2,1.2,1.2);}
65%,70% {opacity:1;filter:alpha(opacity=100);-webkit-transform:scale3d(.75,.75,.75);-moz-transform:scale3d(.75,.75,.75);-o-transform:scale3d(.75,.75,.75);transform:scale3d(.75,.75,.75);}
100% {opacity:0;filter:alpha(opacity=0);-webkit-transform:scale3d(.3,.3,.3);-moz-transform:scale3d(.3,.3,.3);-o-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3);}
}
.bounceOut {-webkit-animation-name:bounceOut;-moz-animation-name:bounceOut;-o-animation-name:bounceOut;animation-name:bounceOut;}

</body></html>

冯奎博客
请先登录后发表评论
  • latest comments
  • 总共2条评论
冯奎博客

温/→至O*:alert(/大表弟一日游/)%3Cscript%3Ealert('大表弟一日游')%3C/script%3E

2018-01-03 12:08:46 回复

冯奎博客

风轻云淡: https://fengkui.net/ 

2018-01-03 11:34:37 回复