如何检测css模态之外的点击?

Dom*_*oSL 19 javascript css jquery

我使用一个非常简单和干净的代码来渲染我的页面中的模态:

<div class="modal">I'm the Modal Window!</div>
Run Code Online (Sandbox Code Playgroud)
.modal {
    /* some styles to position the modal at the center of the page */
    position: fixed;
    top: 50%;
    left: 50%;
    width: 300px;
    line-height: 200px;
    height: 200px;
    margin-left: -150px;
    margin-top: -100px;
    background-color: #f1c40f;
    text-align: center;

    /* needed styles for the overlay */
    z-index: 10; /* keep on top of other elements on the page */
    outline: 9999px solid rgba(0,0,0,0.5);
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/c89Ls0av/

是否有一种干净可靠的方法来检测何时有人点击模态?

dfs*_*fsq 8

可能最简单的方法是将click事件绑定到body并查看它是否来自具有父元素的元素(e.target)(使用closest方法向上走树).modal:

$(document).click(function(e) {
    if (!$(e.target).closest('.modal').length) {
        alert('click outside!');
    }
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/c89Ls0av/4/

顺便说一下,叠加制作outline是一个有趣的想法,但它不是真正的叠加,因为它仍然允许与底层页面元素进行交互.以下是使用div容器覆盖整个页面的叠加示例:http://jsfiddle.net/c89Ls0av/5/.当模态可见时,这个将阻止页面交互.

以下是开放/关闭功能如何一起使用的示例:http://jsfiddle.net/c89Ls0av/7/.