【问题标题】:Multiple modals on with same element name on same page在同一页面上具有相同元素名称的多个模式
【发布时间】:2021-01-22 05:40:36
【问题描述】:

我正在努力做到这一点,当用户在模式之外点击时,它会关闭它。到目前为止,它只适用于第一个模态,而不是第二个。

这是我的代码:

$(window).click(function(e){
    $('.reportModal').each(function(){
        var modal = $(this);
        if (e.target == modal) {
            $('.reportModal').fadeOut();
        }
    });
    //if (e.target == $('.reportModal')[0] || e.target == ) {
    //    $('.reportModal').fadeOut();
    //}
});

我想让它对所有人都有效。任何帮助表示赞赏。谢谢。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    当用户在模态框外点击时,它会关闭它。

    所以...这也可以这样解释:

       如果用户点击的元素没有具有模态类的父元素...

    现在您可以单击打开模态,在 :visible" 条件下应该“延迟”一点。

    这是一个快速制作的演示:

    $("button.open").on("click", function() {
      let modal = $("." + $(this).data("target"))
      setTimeout(function() {
        modal.fadeIn();
      }, 200)
    })
    
    
    $(document).on("click", function(e) {
    
      if ($(".reportModal").is(":visible") && $(e.target).closest(".reportModal").length === 0) {
        $(".reportModal").fadeOut(); // Whichever the opened one is... Close them all!
      }
    });
    .reportModal {
      display: none;
      position: fixed;
      top: 30%;
      left: 45%;
      border: 1px solid grey;
      border-radius: 30px;
      padding: 2em;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="reportModal one">
      <div>My custom modal #1</div>
    </div>
    <button class="open" data-target="one">open modal #1</button>
    
    <div class="reportModal two">
      <div>My custom modal #2</div>
    </div>
    <button class="open" data-target="two">open modal #2</button>

    【讨论】:

    • 谢谢!虽然我不得不将代码更改为长度 === 1,因为这意味着 1 是开放的,对吗?
    • no.. 如果 length 在上述条件中为 1,则用户在模态框内单击,因为 $(e.target).reportModal 的子级。
    • 我尝试了代码,但它触发了模态淡入淡出
    • 关闭模式的正确方法是.modal("hide")。如果你想要淡化效果,here is another answer
    • 您提供的代码有效,因为它关闭了两者 - 但是当我在模式内部单击时,它也会消失,尽管我必须输入 === 1。我也没有使用引导版本
    【解决方案2】:

    由于它只有两个模态,我决定通过它的数组位置来抓取元素:

    $(window).click(function(e){
        if (e.target == $('.reportModal')[0] || e.target == $('.reportModal')[1]) {
            $('.reportModal').fadeOut();
        }
    });
    

    【讨论】:

    • 也许你测试了一个空的模式...尝试使用一个不应在内部关闭它的按钮;)或者在内部使用一个简单的div...
    猜你喜欢
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2014-05-20
    • 2019-02-15
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    相关资源
    最近更新 更多