自定义JavaScript的alert()弹出框样式

JavaScript原始的 alert()弹出框效果很差。

于是想着自定义这个原始alert()的显示样式。

JQuery方式实现代码如下:

<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
    (function () {
        window.alert = function (text) {
            //解析alert内容中的换行符
            text = text.toString().replace(/\\/g, '\\').replace(/\n/g, '<br />').replace(/\r/g, '<br />');

            // 自定义DIV弹窗
            var alertdiv = '<div id="alertdiv" style="position:absolute; display:none ; overflow:hidden;  padding:10px 10px 8px; top: 50%; left: 50%; text-align:center; line-height:22px; background-color:#DDE4EE; border:1px solid #ccc">' + text + '<br /><input type="submit" name="button" id="button" value="确定" style="margin-top:8px;" onclick="$(this).parent().remove(); " /></div>';
            $(document.body).append(alertdiv);

            // 设置偏移数值,实现垂直和水平居中
            $("#alertdiv").css({
                "margin-left": $("#alertdiv").width() / 2 * (-1) - 20,
                "margin-top": $("#alertdiv").height() / 2 * (-1) - 20
            });

            // 显示
            $("#alertdiv").show();
        };
    })();
</script>

<input type="submit" name="button" id="button" value="点击" onclick='alert("这是alert弹窗\n支持\\n换行符")' />

1条评论

l
luka-chen says: 回复

artDialog可以玩玩

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

昵称 *