单击子分区外部时关闭灯箱

Close lightbox on click outside of the child div

本文关键字:分区 外部 单击      更新时间:2023-09-26

我在不使用jquery插件的情况下创建了一个灯箱,现在我试图通过单击close按钮或单击白色区域(.white_content)之外的任何其他位置来关闭它
Jsfidle示例

<button onclick="document.getElementById('lightbox').style.display='inline';">
    Show lightbox
</button>
<!-- LIGHTBOX CODE BEGIN -->
<div id="lightbox" class="lightbox" style="display:none">
    <div class="white_content">
        <a href="javascript:void(0)" onclick="document.getElementById('lightbox').style.display='none';" class="textright">Close</a>
            <p>Click anywhere to close the lightbox.</p>
            <p>Use Javascript to insert anything here.</p>
    </div>
</div>
<!-- LIGHTBOX CODE END -->

虽然这并不是我想要的。我希望只有当我点击灯箱的黑暗区域而不是白色容器(.white_content)时才关闭它,但我听说event.propation可能是一个不好用的东西,所以下面是我如何关闭灯箱

$(document).on('click', function(event) {
  if (!$(event.target).closest('button').length) {
    $(".lightbox").hide();
  }
});

您可以像下面的一样更改您的条件

$(document).on('click', function(event) {
    if ($(event.target).has('.white_content').length) {
        $(".lightbox").hide();
    }
});

大多数lightbox脚本都使用两个div-s,内容和覆盖。覆盖层是为了防止用户点击页面的内容,也可以使用点击覆盖层来关闭灯箱。

HTML:

<div id="lightbox"> LIGHTBOX CONTENT </div>
<div id="overlay"></div>

JS:

$( '#overlay, #close').on('click', function(event) {
    $("#lightbox, #overlay").hide();
});
$( '#show').on('click', function(event) {
    $("#lightbox, #overlay").show();
});

示例

您希望在任何不针对灯箱或其子对象的单击时关闭灯箱。您现有的代码非常接近:

$(document).on('click', function(event) { 
    if (!$(event.target).closest('button').length &&
        !$(event.target).closest('.white_content').length) {
        $(".lightbox").hide();
    }
});

$(document).on('click', function(event) { 
    if (!$(event.target).closest('button').length &&
        !$(event.target).closest('.white_content').length) {
	    $(".lightbox").hide();
    }
});
.textright {
    float: right;
}
.lightbox {
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:rgba(0, 0, 0, .8);
}
.white_content {
    position: absolute;
    top: 25%;
    left: 25%;
    width: 50%;
    height: 50%;
    padding: 16px;
    border: 5px solid gray;
    background-color: white;
    z-index:1002;
    overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="document.getElementById('lightbox').style.display='inline';">
    Show lightbox
</button>
<!-- LIGHTBOX CODE BEGIN -->
<div id="lightbox" class="lightbox" style="display:none">
    <div class="white_content">
        <a href="javascript:void(0)" onclick="document.getElementById('lightbox').style.display='none';" class="textright">Close</a>
            <p>Click anywhere to close the lightbox.</p>
            <p>Use Javascript to insert anything here.</p>
    </div>
</div>
<!-- LIGHTBOX CODE END -->

我还建议使用一个类来表示灯箱是否可见,而不是直接更改显示属性;这样检查时会更清楚。比较$el.is('.active')$(el).css('display') == 'inline'