点击隐藏显示和点击body空白处隐藏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{margin:0; padding:0;} .btn{background:#BF8B8B; width: 150px; height: 30px; line-height: 30px; margin: 0 auto; text-align: center; border-radius: 10px; display: block; text-decoration: none; color: #fff; font-size: 16px;} .pop{ width: 200px; height: 150px; margin: 20px auto; background: red; display: none; } </style> </head> <body> <a href="javascript:;" class="btn">点击</a> <div class="pop">弹窗显示</div> <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $(".btn").click(function(event) { if ($(".pop").is(":hidden")) { $(".pop").show(); } else { $(".pop").hide(); } event.stopPropagation(); }); $('body').click(function() { if (!$(".pop").is(":hidden")) { $(".pop").hide(); } }); }) </script> </body> </html>
效果图:
第二:
var publicPopWrap = $("#publicPopWrap");//弹窗外层 var popShowBtn = $("#popShowBtn");//获取点击按钮 popShowBtn.on("click",function(){ publicPopWrap.show(); }) //除了弹窗内容框内,点击任意位置弹窗隐藏 publicPopWrap.on("click",function(e){ if ($(e.target).closest("#publicPop").length > 0) { $(this).show(); } else { $(this).hide(); } })
//点击空白处隐藏弹出层(用这个)
$(document).click(function(event){ let _con = $("#zhwnlPopCon") // 设置目标区域 if(!_con.is(event.target) && _con.has(event.target).length === 0){ // Mark 1 bindPopupZhwnl.hide(); } });
/* Mark 1 的原理:
判断点击事件发生在区域外的条件是:
1. 点击事件的对象不是目标区域本身
2. 事件对象同时也不是目标区域的子元素
*/
https://www.yisu.com/zixun/183999.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>点击空白处关闭弹出层</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> #box{width:300px;height:200px;border:1px solid #000;display:none;} .btn{color:red;} </style> <script type="text/javascript" src="http://www.internetke.com/public/js/jquery.js"></script> <script type="text/javascript"> $(function(){ $(".btn").click(function(event){ var e=window.event || event; if(e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBubble = true; } $("#box").show(); }); $("#box").click(function(event){ var e=window.event || event; if(e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBubble = true; } }); document.onclick = function(){ $("#box").hide(); }; }) </script> </head> <body> <div id="box"></div> <span class="btn">点击此处打开弹出层</span><br>点击空白处关闭弹出层 </body> </html>