美文网首页
修改系统alert样式,以及判断一个Dom元素是否存在的方法

修改系统alert样式,以及判断一个Dom元素是否存在的方法

作者: 无聊肥猫 | 来源:发表于2018-02-08 11:11 被阅读15次

废话不多说,直接上代码:
common.js

// 覆盖系统alert()函数
// e:弹窗的具体信息
function alert(e){
    $("body").append('<div id="msg"><div id="msg_top">信息<span class="msg_close">×</span></div><div id="msg_cont">'+e+'</div><div class="msg_close" id="msg_clear">确定</div></div>');
    $(".msg_close").click(function (){
        $("#msg").remove();
    });
}

common.css

/* alert弹窗样式 */
#msg{ width:266px; position: fixed; z-index:999; top: 49%; margin-top:-80px; left:50%; margin-left:-133px; background:#fff; box-shadow:5px 5px 8px #999; font-size:17px; color:#666; border:1px solid #f8f8f8; text-align: center; line-height: 2rem; display:inline-block; padding-bottom:20px; border-radius:2px; }
#msg_top{ color: #fff; background:#ec9e49; padding:5px 15px 5px 20px; text-align:center; }
#msg_top span{ font-size:22px; float:right; cursor:pointer; }
#msg_cont{ padding:15px 20px 20px; text-align:center; font-size: 14px; }
#msg_clear{ display:inline-block; width: 150px;  height: 30px; color:#fff; padding:1px 15px; background:#ec9e49; border-radius:15px;  margint:20px auto;  cursor:pointer; }

只要在html页面中引入这两个文件,就可以实现想要的效果。但是会遇到一个问题,就是可以多次调用alert()弹出多个窗口,因此我们需要加一个判断,ID为msg的DOM元素存在则直接return

刚开始我是这样写的:

function alert(e){
    if($('#msg')) {
        return;
    }
    $("body").append('<div id="msg"><div id="msg_top">信息<span class="msg_close">×</span></div><div id="msg_cont">'+e+'</div><div class="msg_close" id="msg_clear">确定</div></div>');
    $(".msg_close").click(function (){
        $("#msg").remove();
    });
}

运行以后发现if条件总是true,打印$('#msg')后发现是这个结果:

打印结果

是一个数组!

也就是说,无论ID为msg的DOM元素是否存在,if条件都成立。因此,要判断ID为msg的DOM元素是否存在,得判断$('#msg')这个数组的长度是否为0,代码如下:


function alert(e){
    if($('#msg').length > 0) {
        return;
    }
    $("body").append('<div id="msg"><div id="msg_top">信息<span class="msg_close">×</span></div><div id="msg_cont">'+e+'</div><div class="msg_close" id="msg_clear">确定</div></div>');
    $(".msg_close").click(function (){
        $("#msg").remove();
    });
}

相关文章

网友评论

      本文标题:修改系统alert样式,以及判断一个Dom元素是否存在的方法

      本文链接:https://www.haomeiwen.com/subject/irzzzxtx.html