Javascript 如何通过在模态窗口外单击来关闭模态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8152819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:53:58  来源:igfitidea点击:

How to close a modal by clicking outside the modal window?

javascriptjquerymodal-dialog

提问by Googlebot

In a very simple jQuery modal, I close the modal by clicking on CLOSE as

在一个非常简单的 jQuery 模态中,我通过单击 CLOSE 来关闭模态

$('#close').click(function(e) {
  e.preventDefault();
  $('#overlay, #alertModalOuter').fadeOut(400, function() {
     $(this).remove();
  });
});

How can I close the modal by clicking whether on CLOSE button (which is inside the modal windows) OR clicking anywhere outside the modal window.

如何通过单击 CLOSE 按钮(位于模态窗口内)或单击模态窗口外的任意位置来关闭模态。

采纳答案by Rich O'Kelly

Changing your function like so should work:

像这样更改您的功能应该可以工作:

    $('#close, #overlay').click(function(e) {
      e.preventDefault();
      $('#overlay, #alertModalOuter').fadeOut(400, function() {
      $('#close').remove();
    });
});

回答by Ryan Charmley

I found it helpful to include:

我发现包含以下内容很有帮助:

$('.item-modal').click(function(e) {
  e.stopPropagation();
});

回答by Stefaan Colman

Add the same click listener to your overlay.

将相同的点击侦听器添加到您的叠加层。

回答by Zack Frank

I know this question pertains to jQuery, but here's how I did this in Vue on my modal component in case anyone finds it helpful. My modal HTML is basically lifted directly from this: https://vuejs.org/v2/examples/modal.html

我知道这个问题与 jQuery 有关,但这是我在 Vue 中对我的模态组件执行此操作的方法,以防有人发现它有帮助。我的模态 HTML 基本上是直接从这里解除的:https: //vuejs.org/v2/examples/modal.html

I set two @clickattributes, one on the outermost modal element (modal-mask) that calls my close()method (which emits the closeevent to the parent component) and one on the actual modal window element (modal-container) that with the .stopevent modifier (@click.stop) to stop the click from bubbling up to the parent element (modal-mask). Works like a charm.

我设置两个@click属性,一个最外面的模态元素(在modal-mask调用我的)close()方法(它发出close的实际模态窗口元素(事件到母部件)和一个modal-container)与该.stop事件修饰符(@click.stop),以阻止气泡点击直到父元素 ( modal-mask)。奇迹般有效。