以下层为目标来关闭一个模态框

Targeting lower layer to close a modal box

本文关键字:一个 模态 目标      更新时间:2023-09-26

我有一个简单的模态框打开像这样:

<div id="social" class="overlay">
  <div class="inner">
    <a class="close" href="#"><span class="icon-close"></span></a>
    CONTENT
 </div>
</div>

CSS:

.overlay { 
    position: fixed; 
    top: 0; 
    left: 0; 
    width: 100%; 
    z-index: 100; 
    background: fade(@black, 75%); 
    display: none;
    z-index: 999;   
}
#social .inner {
    margin: 0 auto;
    z-index: 1000;  
    width: 380px;
}

这里是JS:

 $(document).ready(function(){
    $("#social").css("height", $(document).height());
    $(".social").click(function(){
        $("#social").fadeIn();
        return false;
    });
    $(".close").click(function(){
        $("#social").fadeOut();
        return false;
    });
});

当有人点击带有close类的链接时,模态框关闭。我想模态框关闭时,有人点击模态框外的任何地方,所以任何地方在覆盖层(z-index:999)。我不知道如何在不影响顶层(z-index:1000)的情况下针对下层(z-index:999)。

我对jQuery了解不多,所以如果你能以新手的方式表达你的建议,那就太好了。谢谢!:)

当叠加被点击时,你可以通过在叠加上附加一个点击事件处理程序来淡出模态框。JSFiddle

HTML

<input type="button" class="social" value="test" />
<div id="social" class="overlay">
    <div class="inner"> 
        <a class="close" href="#">
            <span class="icon-close">X</span>
        </a>
        CONTENT
    </div>
</div>
CSS

.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 100;
    background: rgba(0, 0, 0, 0.5);
    display: none;
    z-index: 999;
}
#social .inner {
    margin: 0 auto;
    z-index: 1000;
    width: 380px;
}
jQuery

 $(document).ready(function () {
     $("#social").css("height", $(document).height());
     $(".social").click(function () {
         $("#social").fadeIn();
         return false;
     });
     $(".close").click(function () {
         $("#social").fadeOut();
         return false;
     });

     //This is the part that handles the overlay click
     $("#social").on('click', function (e) {
         if (e.target == this) {
             $(this).fadeOut();
         }
     });
 });