简洁的弹框JS

使用

通过src或require引入js文件,会返回一个dialog对象,包含两个方法。

  • dialog.base(params)
  • dialog.confirm(params)
基本参数
参数说明类型默认值
titleDialog 的标题string
widthDialog 的大小string500px
marginTopDialog CSS 中的 margin-top 值(‘center’时居中)string10%
body_htmlDialog body 的内容区string-
footer_htmlDialog footer 的内容区string-
modal是否需要遮罩层booleantrue
close-on-click-modal是否可以通过点击 modal 关闭 Dialogbooleantrue
show-close是否显示关闭按钮booleantrue
fnQueryconfirm 中确定按钮回调函数function-

dialog.base({
    body_html: '<span>这是一段信息</span>'
});

image

dialog.confirm({
    body_html: '<span>这是一段信息</span>'
}); 

image

/*
    弹出框
    ayguo
 */


;(function(global){

    "use strict"


    if(![].inArray){
        Array.prototype.inArray = function(item){
            var pos = -1;
            for(var i = 0, len = this.length; i < len; i++){
                if(this[i] === item) {
                    pos = i;
                    break;
                }
            }

            return pos;
        }
    }

    if(!''.trim){
        String.prototype.trim = function(){
            return this.replace(/^\s+|\s+$/, '');
        }
    }

    // tools
    var makeMap = function(arr, lowerCase){
        var map = new Object();
        for(var i = 0, len = arr.length; i < len; i++){
            map[arr[i]] = true;
        }

        return lowerCase 
            ? function(val){ return map[val.toLowerCase()]; }
            : function(val){ return map[val]; }

    },
    /*

     */
    extend = function(to, from){
        for(var i in from){
            to[i] = from[i];
        }
        return to;
    },
    /*
        添加事件
     */
    addEvent = function(ele, type, fn, bubble){
        if(!ele) return;
        typeof bubble == 'undefined' && (bubble = false);

        if('addEventListener' in ele){
            ele.addEventListener(type, fn, bubble);
        }else if('attachEvent' in ele){
            ele.attachEvent('on' + type, fn);
        }else{
            ele['on' + type] = fn;
        }
    },
    /*
        移除事件
     */
     removeEvent = function(ele, type, fn, bubble){
        if(!ele) return;
        typeof bubble == 'undefined' && (bubble = false);

        if('removeEventListener' in ele){
            ele.removeEventListener(type, fn, bubble);
        }else if('detachEvent' in ele){
            ele.detachEvent('on' + type, fn);
        }else{
            ele['on' + type] = null;
        }
     },
    /*
        给元素添加对应的class
        el      element
        str     string
     */
    addClass = function(el, str){
        var classArr = str.split(' ');

        for(var i = 0, len = classArr.length; i < len; i++){
            if('classList' in el){
                el.classList.add(classArr[i]);
            }else{
                var cls = el.className,
                    arr = cls.split(' ');

                if(arr.inArray(classArr[i]) == -1){
                    arr.push(classArr[i]);
                    el.className = arr.join(' ').trim();
                }
            }
        }
    },

    /*
        从元素上移除对应的class
        el      elemtn
        str     string
     */
    removeClass = function(el, str){
        var classArr = str.split(' ');

        for(var i = 0, len = classArr.length; i < len; i++){
            if('classList' in el){
                el.classList.remove(classArr[i]);
            }else{
                var cls = el.className,
                    arr = cls.split(' '),
                    pos;

                if((pos = arr.inArray(classArr[i])) != -1){
                    arr.splice(pos, 1);
                    el.className = arr.join(' ');
                }
            }
        }

    };

    /*
        通过属性获取对象
        getByAttr('role', 'ele_dialog', document)
     */
    function getByAttr(attrName, attrVal, parentNode){
        parentNode = document || parentNode;

        if(parentNode.querySelectorAll){
            var attrStr = '['+attrName+ ( attrVal ? '='+attrVal : '' ) +']';
            return parentNode.querySelectorAll(attrStr);
        }else{
            var arr = [];
            var nodeLists = parentNode.getElementsByTagName('*');

            for(var i = 0, len = nodeLists.length; i < len; i++){
                var attr = nodeLists[i].getAttribute(attrName);
                if( attr != null && (attrVal === undefined || attrVal !== undefined && attr === attrVal) ){
                    arr.push(nodeLists[i]);
                }
            }

            return arr;
        }
    }

    /*
        添加弹框对应的样式
     */
    (function addStyle(){
        var style = document.createElement('style'),
            head = document.head || document.getElementsByTagName('head')[0];

        style.id = 'dialog_style';
        style.innerHTML = [
            '[role=ele_dialog]{ position: fixed; top:0; left: 0; bottom: 0; right: 0; overflow: auto; margin: 0; z-index: 2000; font-size: 14px;}',
            '[role=ele_mask]{ position: fixed; top:0; left: 0; z-index: 2001; width: 100%; height: 100%; background-color: #000; filter: alpha(opacity=50); opacity:.5; }',
            '[role=ele_inner]{ position: absolute; z-index: 2005; background-color: #fff; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,.3); box-sizing: border-box; }',
            '[role=ele_header]{ padding: 20px 20px 0; position: relative;}',
            '[role=ele_title]{ font-size: 16px;}',
            '[role=ele_close]{ color: #c0ccda; font-size: 13px; text-decoration: none; position: absolute; right: 20px; top: 20px;}',
            '[role=ele_close]:hover{ color: #20a0ff;}',
            '[role=ele_body]{ padding: 30px 20px; color: #475669;}',
            '[role=ele_footer]{ padding: 10px 20px 15px; text-align: right; box-sizing: border-box;}',
            '[role=button_wrap] button{ display: inline-block; cursor: pointer; line-height: 1; background-color: #fff; color: #1f2d3d; border: 1px solid #c0ccda; text-align: center; outline: none; padding: 10px 15px; font-size: 14px; border-radius: 4px; margin: 0; box-sizeing: border-box;}',
            '[role=button_wrap] [role="ele_cancel"]:hover{ border-color: #20a0ff; color: #20a0ff;}',
            '[role=button_wrap] [role="ele_query"]{ background: #20a0ff;border-color: #20a0ff; color: #fff; margin-left: 20px;}',
            '[role=button_wrap] [role="ele_query"]:hover{ background: #4db3ff; border-color: #4db3ff;}'
        ].join('\n');   

        head.appendChild(style);
    })();



    /*
        参数                      说明                                          类型                                      默认值
        title                       Dialog 的标题                                  string                                      —
        width                       Dialog 的大小                                  string                                      '500px'
        marginTop                   Dialog CSS 中的 margin-top 值('center'时居中) string                                      10%
        body_html                   Dialog body 的内容区
        footer_html                 Dialog footer 的内容区
        modal                       是否需要遮罩层                                 boolean                                     true
        close-on-click-modal        是否可以通过点击 modal 关闭 Dialog                boolean                                     true
        show-close                  是否显示关闭按钮                                boolean                                     true
     */
    var D = function(args){
        var _this = this;
        typeof args == 'undefined' && (args = {});

        this.title                          = args.title || '提示';
        this.width                          = args.width || '500px';
        this.marginTop                      = args.marginTop || '10%';
        this.body_html                      = args.body_html || '';
        this.footer_html                    = args.footer_html || '';
        this.modal                          = args.modal || true;
        this['close-on-click-modal']        = args['close-on-click-modal'] || true;
        this['show-close']                  = args['show-close'] || true;

        var ele_dialog = document.createElement('div'),
            html = [this.modal ? '<div role="ele_mask"></div>' : '',
                    '<div role="ele_inner">',
                        '<div role="ele_header">',
                            '<span role="ele_title">'+this.title+'</span>',
                            this['show-close'] ? '<a role="ele_close" href="javascript:;">关闭</a>' : '',
                        '</div>',
                        '<div role="ele_body">'+this.body_html+'</div>',
                        '<div role="ele_footer">'+this.footer_html+'</div>',
                    '</div>'].join('\n');

        // append
        ele_dialog.innerHTML = html;
        ele_dialog.setAttribute('role', 'ele_dialog');

        document.body.appendChild(ele_dialog);

        var ele_inner = getByAttr('role', 'ele_inner', ele_dialog)[0];
        ele_inner.style.width = this.width;

        var inner_width = ele_inner.offsetWidth,
            inner_height = ele_inner.offsetHeight,
            win_width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
            win_height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;


        // dialog 的位置 
        ele_inner.style.marginTop = this.marginTop == 'center' ? parseInt(( win_height - inner_height ) / 2) + 'px' : this.marginTop;   
        ele_inner.style.marginLeft = parseInt(( win_width - inner_width ) / 2) + 'px';  

        // 点击蒙层
        addEvent(getByAttr('role', 'ele_mask', ele_dialog)[0], 'click', function(){
            if(_this['close-on-click-modal']) document.body.removeChild(ele_dialog);
        });

        // 点击关闭按钮
        addEvent(getByAttr('role', 'ele_close', ele_dialog)[0], 'click', function(){
            // typeof this.fnClose == 'function' && this.fnClose();
            document.body.removeChild(ele_dialog);
        });



        return ele_dialog;  
    }


    var dialog = {
        // 基础弹框
        base: function(params){
            return new D(params);
        },
        // confirm弹框
        confirm: function(params){

            // params.fnQuery 为点击确定按钮的回调函数
            var box = new D(extend(params, {
                footer_html: '<span role="button_wrap"><button type="button" role="ele_cancel">取 消</button><button type="button" role="ele_query">确 定</button></span>'
            }));

            // 点击取消按钮
            addEvent(getByAttr('role', 'ele_cancel', box)[0], 'click', function(){
                document.body.removeChild(box);
            });

            // 点击确定按钮
            addEvent(getByAttr('role', 'ele_query', box)[0], 'click', function(){
                typeof params.fnQuery == 'function' && params.fnQuery();
            });

            return box;
        }
    }


    if ( typeof define === "function" && define.amd ) {
        define( "dialog", [], function () { return dialog; } );
    } else {
        global.dialog = dialog;
    }


})(window);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值