实现点击空白关闭模态框

监听document,当用户点击后,获取点击的id,如果id不是modal则关闭modal
当然还需要注意的是要阻止modal的冒泡事件,不然modal一弹出来之后就又关闭了。

停止冒泡

$("#modal").bind("click", function(event) {
    
    
if (event && event.stopPropagation) {
    
    
event.stopPropagation();
} else {
    
    
event.cancelBubble = true;
}

});

监听document

$(document).one("click", function(e){
    
    
var $target = $(e.currentTarget);
if ($target.attr("id") != "modal") {
    
    
$("#modal").css("display", "none");
}
});

原生JS参考我的另一篇文章:
https://blog.csdn.net/qq_42535651/article/details/104127120

猜你喜欢

转载自blog.csdn.net/qq_42535651/article/details/104017559