弹窗和遮罩层的显示隐藏及空白区域关闭

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Commpatible" content="IE=edge">
    <title>HTML遮罩层</title>
    <style>
        body{
            background: aqua;
        }
        .shade{
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            width: 100%;
            height: 100%;
            background: black;
            opacity: 0.6;
            display: none;
        }
        .dialog{
            display: none;
            position: relative;
            width: 200px;
            height: 200px;
            background: lightcoral;
        }
        .btn{
            position: absolute;
            width: 50px;
            height: 50px;
            top: 40px;
            left: 200px;
            background: #c1f088;
        }
    </style>
</head>
<body>
 <div class="shade"></div>
 <div class="wrap">
    弹窗展示
 </div>
  <div class="dialog">
      <div class="content">内容区</div>
      <div class="btn">按钮</div>
</div>
 <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.slim.js"></script>
 <script>
     // 弹窗显示
     $('.wrap').click(function () {
         $('.shade').show()
         $('.dialog').show()
     })
     // 点击关闭按钮,弹窗隐藏
    $('.btn').click(function () {
        $('.shade').hide()
        $('.dialog').hide()
    })
     // 点击空白区域,弹窗隐藏
     $(document).mouseup(function(e){
         var _con = $('.dialog ');   // 设置目标区域
         // 点击事件的对象不是目标区域本身
         // 事件对象不是目标区域的子元素
         if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
             console.log(e)
             console.log(e.target)
             $('.shade').hide()
             $('.dialog').hide()
         }
     });

 </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/renzm0318/p/10679260.html