关于javascript:如何检测css模式之外的点击?

How to detect clicks outside of a css modal?

本问题已经有最佳答案,请猛点这里访问。

我使用一个非常简单和干净的代码在我的页面中呈现模式:

1
I'm the Modal Window!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.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);
}

http://jsfiddle.net/c89ls0av/

有没有一种干净可靠的方法来检测有人在模式外点击?


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

1
2
3
4
5
$(document).click(function(e) {
    if (!$(e.target).closest('.modal').length) {
        alert('click outside!');
    }
});

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

顺便说一下,使用outline创建的覆盖是一个有趣的想法,但它不是真正的覆盖,因为它仍然允许与底层页面元素交互。下面是DIV容器覆盖整个页面的覆盖示例:http://jsfiddle.net/c89ls0av/5/。当模式可见时,此选项将阻止页面交互。

下面是一个如何一起使用打开/关闭功能的示例:http://jsfiddle.net/c89ls0av/7/。


答案会很好。但是,如果您想对对话框做些什么,可以查看jquery ui对话框。它为您提供了许多对话框选项,您可以根据需要进行配置。

http://jqueryui.com/dialog/对话框/


没有jQuery

1
2
3
4
5
6
7
document.addEventListener('click', function (e) {
  if(e.target.className === 'modal'){
     alert('clicked in');
  }else {
    alert('clicked out');
  }
}, false);

过来看:http://jsbin.com/totoonopili/1/edit?HTML、CSS、JS、输出


在JavaScript框架的帮助下,这非常容易。

遵循以下步骤:

  • 将一个单击事件附加到关闭或隐藏模式的文档。
  • 将单独的单击事件附加到停止单击传播的窗口。
  • 例子:

    1
    2
    3
    4
    5
    6
    $('html').click(function(){
        $('.modal').hide();
    });
    $('.modal').click(function(e){
        e.stopPropagation();
    });

    http://jsfiddle.net/c89ls0av/3/

    警告!停止传播会导致奇怪的行为