【问题标题】:How to detect clicks outside of a css modal? [duplicate]如何检测css模式之外的点击? [复制]
【发布时间】:2015-01-13 02:07:24
【问题描述】:

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

<div class="modal">I'm the Modal Window!</div>

.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/

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

【问题讨论】:

  • 你需要使用javascript
  • 你有没有尝试过?

标签: javascript jquery css


【解决方案1】:

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

$(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/

【讨论】:

  • 如果模态框后面有内容,那就可以了。将'body' 替换为document,似乎不管怎样都运行良好。
  • 这个答案引入了一大堆不在他的小提琴中的段落。您将如何解决 OP 中的问题?
  • @RickHitchcock 非常正确,我忘记了正文只会占用内容所需的高度。谢谢!
  • @BenSmith 它实际上不适用于body 点击事件。见上面的评论。现在我将其修复为document。感谢您的评论!
  • @DomingoSL 顺便说一下,这里是一个真实覆盖的例子:jsfiddle.net/c89Ls0av/5
【解决方案2】:

在 javascript 框架的帮助下,这很容易。

按照以下步骤操作:

  1. 将单击事件附加到关闭或隐藏模式的文档。
  2. 将单独的单击事件附加到停止单击传播的窗口。

例子:

$('html').click(function(){
    $('.modal').hide();
});
$('.modal').click(function(e){
    e.stopPropagation();
});

http://jsfiddle.net/c89Ls0av/3/

警告!Stopping propagation 可能会引入奇怪的行为

【讨论】:

    【解决方案3】:

    Dfsq 答案会很好用。但如果你想与对话框有关,你可以看看 jQuery ui 对话框。它为您提供了许多带有对话框的选项,您可以根据需要进行配置。

    http://jqueryui.com/dialog/

    【讨论】:

      【解决方案4】:

      没有 jQuery

      document.addEventListener('click', function (e) {
        if(e.target.className === 'modal'){
           alert('clicked in');
        }else {
          alert('clicked out');
        }
      }, false);
      

      检查一下:
      http://jsbin.com/totonopili/1/edit?html,css,js,output

      【讨论】:

      • 有点复杂。如果您在模式中嵌套了 HTML 元素(p、链接、按钮等),e.target 将不再是 modal。所以你需要实现closest 功能。通常使用while循环,上树检查parentNode
      猜你喜欢
      • 1970-01-01
      • 2023-03-02
      • 2014-09-29
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2013-06-18
      • 2013-09-24
      • 2010-09-14
      相关资源
      最近更新 更多