简体   繁体   English

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

[英]How to close a modal by clicking outside the modal window?

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.如何通过单击关闭按钮(位于模态窗口内)或单击模态窗口外的任何位置来关闭模态。

Changing your function like so should work:像这样改变你的功能应该有效:

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

I found it helpful to include:我发现包括以下内容很有帮助:

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

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

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.我知道这个问题与 jQuery 有关,但这是我在 Vue 中对我的模态组件执行此操作的方法,以防有人发现它有帮助。 My modal HTML is basically lifted directly from this: https://v2.vuejs.org/v2/examples/modal.html我的模态 HTML 基本上是直接从这里提取的: https ://v2.vuejs.org/v2/examples/modal.html

I set two @click attributes, one on the outermost modal element ( modal-mask ) that calls my close() method (which emits the close event to the parent component) and one on the actual modal window element ( modal-container ) that with the .stop event modifier ( @click.stop ) to stop the click from bubbling up to the parent element ( modal-mask ).我设置了两个@click属性,一个在最外层的模态元素( modal-mask )上,它调用我的close()方法(它向父组件发出close事件),另一个在实际的模态窗口元素( modal-container )上使用.stop事件修饰符 ( @click.stop ) 来阻止点击冒泡到父元素 ( modal-mask )。 Works like a charm.奇迹般有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM