【问题标题】:Auto close modal on click outside of window, but keep it open if clicked inside the modal window [duplicate]在窗口外单击时自动关闭模态,但如果在模态窗口内单击则保持打开状态[重复]
【发布时间】:2018-10-04 06:41:32
【问题描述】:

当用户在模式之外点击时,我试图自动关闭模式。当用户在模态中单击时,我确实希望模态保持打开状态,但是我遇到了一些问题(它不会工作)。

目前,如果我单击屏幕上的任意位置,模式将关闭。这个模态是用 tailwind css 和 http://jquerymodal.com/ 构建的

我的模态代码:

<div id="interestModal" class="modalDialog invisible animated fadeIn fixed z-50 pin overflow-auto bg-smoke-dark flex">
  <div class="animated fadeInUp fixed shadow-inner max-w-md md:relative pin-b pin-x align-top m-auto justify-end md:justify-center p-8 bg-white md:rounded w-full md:h-auto md:shadow flex flex-col">
    <h2 class="text-4xl text-center font-hairline md:leading-loose text-grey md:mt-8 mb-4">Question!</h2>
    <p class="text-xl leading-normal mb-8 text-center">
      Is this Working???
    </p>
    <div class="inline-flex justify-center">
      <button id="interestClose" class="bg-grey-lighter flex-1 border-b-2 md:flex-none border-green ml-2 hover:bg-green-lightest text-grey-darkest font-bold py-4 px-6 rounded">
        Absolutely
      </button>
      <button @click="toggleModal" class="bg-grey-lighter flex-1 md:flex-none border-b-2 border-red ml-2 hover:bg-red-lightest text-grey-darkest font-bold py-4 px-6 rounded">
        Not so much
    </button>
  </div>
    <a href="#" id="closeModal" rel="modal:close" class="absolute pin-t pin-r pt-4 px-4"><svg class="h-12 w-12 text-grey hover:text-grey-darkest" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>Close</title><path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg></a>
  </div>
</div>

我的 jQuery 来处理模态:

$(document).ready(function () {
    setTimeout(function(){
        $('#interestModal').fadeIn(1000).removeClass('invisible');
    }, 10000);

    $('#interestModal .modalDialog').on('click', function(e)){
      e.addClass('invisible');
    });

});

【问题讨论】:

  • 这个插件已经有你想要的了,check出来
  • 由于#interestModal.modalDialog 似乎是同一个元素,因此无需在$('#interestModal .modalDialog') 中使用类名...此外,两者之间也不要使用空格,因为这将寻找该类的后代。
  • @Pedram 大部分时间都在使用它,但是它在某些需要运行的类中与 tailwindcss 发生冲突,因此是自定义要求

标签: javascript jquery tailwind-css


【解决方案1】:

你可以这样做:

$(document).click(function(e) {
    var modal_id_count = $(e.target).parents('#interestModal').length;
    if (modal_id_count < 1) {
        $("#interestModal").addClass('invisible');                        
    }
});

【讨论】:

  • 即使我点击它内部,这仍然会关闭模式
  • 好的 @ShawnWilson 让我仔细检查一下。
  • @ShawnWilson,您可以尝试在答案中使用我更新的代码吗?
  • 感谢您接受@ShawnWilson 的回答。
猜你喜欢
  • 1970-01-01
  • 2017-07-12
  • 2012-04-08
  • 2014-02-02
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多