原生JS自定义alert和confirm

预览图

在这里插入图片描述
在这里插入图片描述

低版本IE6下按钮无hover效果
话不多说,上代码

image目录下的png图片资源

dialog-info.png
dialog-warning.png
dialog-error.png
dialog-help.png

目录结构

目录结构

CSS代码

dialog.css

html,
body {
    margin: 0;
    padding: 0;
}
body {
    font-family: 'Microsoft Yahei', '微软雅黑', Arial, sans-serif;
    _background-attachment: fixed;
    _background-image: url(about:blank);
}
.dialog-layer {
    -moz-user-select: none;
    -o-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor: default;
}
.dialog-layer {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9900;
    background: rgba(64, 64, 64, 0.01);
    overflow: hidden;
}

.dialog-layer .dialog-mask {
    width: 100%;
    height: 100%;
    background: #202020;
    opacity: 0.01;
    filter: Alpha(opacity = 1);
}

.dialog-layer .dialog-container {
    position: absolute;
    width: 480px;
    height: 320px;
    left: 50%;
    top: 50%;
    margin: -160px 0 0 -240px;
    background: #FDFDFD;
    border-radius: 0;
    overflow: visible;
    -webkit-box-shadow: 0 0 5px #20A0FD;
    -moz-box-shadow: 0 0 5px #20A0FD;
    box-shadow: 0 0 5px #20A0FD;
}
.dialog-layer .dialog-header {
    height: 52px;
    background-color: #FDFDFD;
    border-bottom: 2px solid #C0C0C0;
    line-height: 52px;
    color: #404040;
    font-weight: bold;
    font-size: 20px;
    text-indent: 0.8em;
    letter-spacing: 2px;
}
.dialog-layer .dialog-body {
    position: relative;
    top: 0;
    left: 0;
    height: 212px;
    overflow: hidden;
}
.dialog-layer .dialog-footer {
    height: 54px;
    background-color: #E0E0E0;
}
.dialog-layer .dialog-move-layer {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}
.dialog-layer .dialog-btn {
    display: block;
    position: absolute;
    bottom: 8px;
    width: 140px;
    height: 38px;
    font-size: 18px;
    line-height: 38px;
    text-align: center;
    color: #FCFCFC;
    font-weight: bold;
    cursor: pointer;
    text-decoration: none;
}
.dialog-layer .dialog-btn-sure {
    background: #0080F0;
    left: 60px;
}
.dialog-layer .dialog-btn-cancel {
    background: #A09090;
    right: 60px;
}
.dialog-layer .dialog-btn-sure:hover {
    background: #0060D0;
}
.dialog-layer .dialog-btn-cancel:hover {
    background: #908080;
}
.dialog-layer .dialog-placeholder {
    display: inline-block;
    *display: inline;
    *zoom: 1;
    width: 20px;
    height: 100%;
    vertical-align: middle;
}
.dialog-layer .dialog-icon {
    display: inline-block;
    *display: inline;
    *zoom: 1;
    width: 72px;
    height: 72px;
    vertical-align: middle;
    margin: 0 20px 0 0;
}
.dialog-layer .dialog-icon.dialog-info {
    background: url(../image/dialog-info.png) 0 0 no-repeat;
}
.dialog-layer .dialog-icon.dialog-warning {
    background: url(../image/dialog-warning.png) 0 0 no-repeat;
}
.dialog-layer .dialog-icon.dialog-error {
    background: url(../image/dialog-error.png) 0 0 no-repeat;
}
.dialog-layer .dialog-icon.dialog-help {
    background: url(../image/dialog-help.png) 0 0 no-repeat;
}
.dialog-layer .dialog-content {
    display: inline-block;
    *display: inline;
    *zoom: 1;
    width: 350px;
    vertical-align: middle;
    word-break: break-all;
    -ms-word-wrap: break-word;
    word-wrap: break-word;
}

ie8-lte.css

.dialog-layer .dialog-container .up-shadow {
    position: absolute;
    width: 480px;
    height: 3px;
    left: 0;
    top: -3px;
    overflow: hidden;
    filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr=#0020A0FD,endColorStr=#7220A0FD,gradientType=0);
}
.dialog-layer .dialog-container .down-shadow {
    position: absolute;
    width: 480px;
    height: 3px;
    left: 0;
    bottom: -3px;
    overflow: hidden;
    filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr=#7220A0FD,endColorStr=#0020A0FD,gradientType=0);
}
.dialog-layer .dialog-container .left-shadow {
    position: absolute;
    width: 3px;
    height: 320px;
    left: -3px;
    top: 0;
    overflow: hidden;
    filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr=#0020A0FD,endColorStr=#7220A0FD,gradientType=1);
}
.dialog-layer .dialog-container .right-shadow {
    position: absolute;
    width: 3px;
    height: 320px;
    right: -3px;
    top: 0;
    overflow: hidden;
    filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr=#7220A0FD,endColorStr=#0020A0FD,gradientType=1);
}

ie6-lte.css

.dialog-layer {
    position: absolute;
    top: expression(this.offsetParent.scrollTop);
    left: expression(this.offsetParent.scrollLeft);
}

Javascript代码

sun-ui.js

(function (window, document) {
    if (window.sunui) {return;}
    var sunui = {};
    var lteIE8 = (function () {return !+"\v1";})();
    sunui.rootPath = (function() {
        var scripts = document.getElementsByTagName('script'),
            script = scripts[scripts.length - 1],
            strJsPath = document.querySelector ? script.src : script.getAttribute('src', 4),
            strJsParentPath = strJsPath.substring(0, strJsPath.lastIndexOf('/'));
        return strJsParentPath;
    })();
    (function () {
        sunui.messager = [];
        sunui.alert = function(title, msg, level, handler) {
            var dialogNode = new DialogNode(), json = null;
            if (typeof title === 'string') {
                json = {title: title, msg: msg, level: (function () {
                    if (typeof level === 'string') {return level;} else if (typeof handler === 'string') {return handler;} else {return null;}
                })(), handler: (function () {
                    if (typeof handler === 'function') {return handler;} else if (typeof level === 'function') {return level;} else {return null;}
                })()};
            } else {json = title;}
            dialogNode.init('alert', json);
            sunui.messager.push(dialogNode);
            if(sunui.messager.length === 1) {dialogNode.show();}
        };

        sunui.confirm = function(title, msg, level, handler) {
            var dialogNode = new DialogNode(), json = null;
            if (typeof title === 'string') {
                json = {title: title, msg: msg, level: (function () {
                    if (typeof level === 'string') {return level;} else if (typeof handler === 'string') {return handler;} else {return null;}
                })(), handler: (function () {
                    if (typeof handler === 'function') {return handler;} else if (typeof level === 'function') {return level;} else {return null;}
                })()};
            } else {json = title;}
            dialogNode.init('confirm', json);
            sunui.messager.push(dialogNode);
            if(sunui.messager.length === 1) {dialogNode.show();}
        };

        function DialogNode() {
            this.dialogModal = null;
            this.dialogContainer = null;
            this.dialogMask = null;
            this.dialogBtnSure = null;
            this.dialogBtnCancel = null;
            this.json = null;
        }

        DialogNode.prototype.init = function (type, json) {
            if (!json || typeof json !== 'object') {throw new Error('参数必须为一个对象');}
            var that = this, div = document.createElement('div');
            json.title = json.title || '提示';
            json.level = json.level || (type === 'confirm' ? 'help' : 'info');
            if (json.level === 'warn') {json.level = 'warning';}
            json.msg = json.msg || '';
            json.yes  = json.yes || '确定';
            json.no  = json.no || '取消';
            that.json = json;

            that.dialogModal = div.cloneNode();
            that.dialogModal.className = 'dialog-layer';
            var dialogModalMask = div.cloneNode();
            dialogModalMask.className = 'dialog-mask';
            that.dialogContainer = div.cloneNode();
            that.dialogContainer.className = 'dialog-container';

            if (lteIE8) {
                (function () {
                    var upShadow = div.cloneNode();
                    upShadow.className = 'up-shadow';
                    var downShadow = div.cloneNode();
                    downShadow.className = 'down-shadow';
                    var leftShadow = div.cloneNode();
                    leftShadow.className = 'left-shadow';
                    var rightShadow = div.cloneNode();
                    rightShadow.className = 'right-shadow';
                    that.dialogContainer.appendChild(upShadow);
                    that.dialogContainer.appendChild(downShadow);
                    that.dialogContainer.appendChild(leftShadow);
                    that.dialogContainer.appendChild(rightShadow);
                })();
            }

            that.dialogModal.appendChild(dialogModalMask);
            that.dialogModal.appendChild(that.dialogContainer);

            var dialogHeader = div.cloneNode();
            dialogHeader.className = 'dialog-header';
            dialogHeader.innerHTML = json.title;

            var dialogBody = div.cloneNode();
            dialogBody.className = 'dialog-body';
            var dialogPlaceholder = div.cloneNode();
            dialogPlaceholder.className = 'dialog-placeholder';
            var dialogIcon = div.cloneNode();
            dialogIcon.className = 'dialog-icon dialog-' + json.level;
            var dialogContent = div.cloneNode();
            dialogContent.className = 'dialog-content';
            dialogContent.innerHTML = json.msg;
            dialogBody.appendChild(dialogPlaceholder);
            dialogBody.appendChild(dialogIcon);
            dialogBody.appendChild(dialogContent);

            var dialogFooter = div.cloneNode();
            dialogFooter.className = 'dialog-footer';

            var dialogMoveLayer = div.cloneNode();
            dialogMoveLayer.className = 'dialog-move-layer';
            that.dialogMask = div.cloneNode();
            that.dialogMask.className = 'dialog-mask';
            that.dialogBtnSure = div.cloneNode();
            that.dialogBtnSure.className = 'dialog-btn dialog-btn-sure';
            that.dialogBtnSure.innerHTML = json.yes;
            if (type === 'alert') {
                that.dialogBtnSure.style.left = '170px';
            } else {
                that.dialogBtnCancel = div.cloneNode();
                that.dialogBtnCancel.className = 'dialog-btn dialog-btn-cancel';
                that.dialogBtnCancel.innerHTML = json.no;
            }
            dialogMoveLayer.appendChild(that.dialogMask);
            dialogMoveLayer.appendChild(that.dialogBtnSure);
            if (type !== 'alert') {
                dialogMoveLayer.appendChild(that.dialogBtnCancel);
            }

            that.dialogContainer.appendChild(dialogHeader);
            that.dialogContainer.appendChild(dialogBody);
            that.dialogContainer.appendChild(dialogFooter);
            that.dialogContainer.appendChild(dialogMoveLayer);
        };

        DialogNode.prototype.show = function () {
            var that = this;
            document.body.appendChild(that.dialogModal);
            that.dialogBtnSure.onclick = function (e) {
                var ev = e || window.event;
                if(ev.stopPropagation) {ev.stopPropagation();} else {ev.cancelBubble = true;}
                if(ev.preventDefault) {ev.preventDefault();} else {ev.returnValue = false;}
                that.dialogModal.parentNode.removeChild(that.dialogModal);
                if(typeof that.json.handler === 'function') {that.json.handler(true);}
                sunui.messager.shift(that);
                that.showNext();
                return false;
            };
            if (that.dialogBtnCancel) {
                that.dialogBtnCancel.onclick = function (e) {
                    var ev = e || window.event;
                    if(ev.stopPropagation) {ev.stopPropagation();} else {ev.cancelBubble = true;}
                    if(ev.preventDefault) {ev.preventDefault();} else {ev.returnValue = false;}
                    that.dialogModal.parentNode.removeChild(that.dialogModal);
                    if(typeof that.json.handler === 'function') {that.json.handler(false);}
                    sunui.messager.shift(that);
                    that.showNext();
                    return false;
                };
            }
            that.dialogModal.onselectstart = function (e) {
                var ev = e || window.event;
                if(ev.stopPropagation) {ev.stopPropagation();} else {ev.cancelBubble = true;}
                if(ev.preventDefault) {ev.preventDefault();} else {ev.returnValue = false;}
            };
            that._moveListener();
        };

        DialogNode.prototype.showNext = function () {
            var that = this;
            if(sunui.messager.length) {sunui.messager[0].show();}
            that = null;
        };

        DialogNode.prototype._moveListener = function () {
            var disX = 0, disY = 0,
                that = this, dialogModal = that.dialogModal, container = that.dialogContainer, el = that.dialogMask,
                doel = el.setCapture ? el : document,
                dialogWidth = window.undefined, dialogHeight = window.undefined;
            el.onmousedown = function (ev) {
                var oEvent = ev || event;
                dialogWidth = dialogWidth || container.offsetWidth;
                dialogHeight = dialogHeight || container.offsetHeight;
                disX = oEvent.clientX - container.offsetLeft;
                disY = oEvent.clientY - container.offsetTop;
                doel.onmousemove = function (ev) {
                    var oEvent = ev || event, l = oEvent.clientX - disX, t = oEvent.clientY - disY;
                    if (l < 1) {l = 1;} else if (l > dialogModal.clientWidth - container.offsetWidth - 1) {l = dialogModal.clientWidth - container.offsetWidth - 1;if (l < 1) {l = 1;}}
                    if (t < 1) {t = 1;} else if (t > dialogModal.clientHeight - container.offsetHeight - 1) {t = dialogModal.clientHeight - container.offsetHeight - 1;if (t < 1) {t = 1;}}
                    container.style.left = l + dialogWidth / 2 + 'px';
                    container.style.top = t + dialogHeight / 2 + 'px';
                    return false;
                };
                doel.onmouseup = function () {doel.onmousemove = null; doel.onmouseup = null; if(el.releaseCapture) {el.releaseCapture();}};
                if(el.setCapture) {el.setCapture();}
                return false;
            };
        };
    })();

    window.sunui = sunui;
})(window, document);

使用方法

HTML代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dialog</title>
    <link rel="stylesheet" href="static/css/dialog.css">
    <!--[if lte IE 8]>
    <link rel="stylesheet" href="static/css/ie8-lte.css">
    <![endif]-->
    <!--[if lte IE 6]>
    <link rel="stylesheet" href="static/css/ie6-lte.css">
    <![endif]-->
</head>
<body>
Dialog测试
</body>
<script src="static/js/sun-ui.js" type="text/javascript"></script>
<script src="static/js/main.js" type="text/javascript"></script>
</html>

Javascript代码示例

(function (window, document) {
    sunui.confirm({
        title: '签退<span style="color: #0060D0">33</span>了',
        msg: '退下吧',
        handler: function (r) {

        },
        level: 'info',
        yes: '遵命!',
        no: '不&emsp;要'
    });
    sunui.alert({
        title: '再见',
        msg: '退下吧<span style="color: #F00000">退下吧</span>',
        handler: function (r) {

        },
        level: 'warn',
        yes: null
    });
    sunui.alert('提示','退下吧<span style="color: #F00000">退下吧</span>', 'error', function (r) {

    });
    sunui.confirm('提示','是不是该<span style="color: #F09000">退下</span>了?', function (r) {
        if (r) {
            sunui.confirm({
                title: '签<span style="color: #0060D0">33</span>退2',
                msg: '退下吧',
                handler: function (r) {

                },
                level: 'warning',
                yes: '遵命!',
                no: '不&emsp;要'
            });
        } else {
            sunui.alert({
                title: '再见4455',
                msg: '退下吧<span style="color: #F00000">退下吧</span>'
            });
        }
    });
    sunui.alert('提示11111','退下吧<span style="color: #F09000">退下吧</span>', function (r) {

    });
})(window, document);

附件

自定义alert和confirm

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值