如何检测Bootstrap模式关闭的方式

时间:2019-01-20 23:42:45

标签: javascript jquery bootstrap-4 bootstrap-modal

我正在将处理程序附加到Bootstrap hidden.bs.modal事件中,以检测何时关闭了模式,但是可以通过多种方式将其关闭:

  1. 通过$('#modal').modal('hide')$('#modal').modal('toggle')明确关闭它;
  2. 单击模式的背景部分(如果允许);
  3. 通过数据属性,例如data-dismiss="modal"

有没有一种方法可以检测出使用了哪个选项?在hidden.bs.modal处理程序e.target中,似乎总是div#modal

1 个答案:

答案 0 :(得分:3)

问题在于,hidden.bs.modal是一个事件,一旦关闭模式便会触发该事件。因此,这不是用户从关闭按钮,边角X或叠加层触发的click事件……

也就是说,您可以使用click事件存储用户点击变量的位置 ,并且在hidden.bs.modal触发后的毫秒内使用该变量。< / p>

演示:

$(document).ready(function(){

  // Variable to be set on click on the modal... Then used when the modal hidden event fires
  var modalClosingMethod = "Programmatically";

  // On modal click, determine where the click occurs and set the variable accordingly
  $('#exampleModal').on('click', function (e) {

    if ($(e.target).parent().attr("data-dismiss")){
      modalClosingMethod = "by Corner X";
    }
    else if ($(e.target).hasClass("btn-secondary")){
      modalClosingMethod = "by Close Button";
    }
    else{
      modalClosingMethod = "by Background Overlay";
    }

    // Restore the variable "default" value
    setTimeout(function(){
      modalClosingMethod = "Programmatically";
    },500);
  });

  // Modal hidden event fired
  $('#exampleModal').on('hidden.bs.modal', function () {
    console.log("Modal closed "+modalClosingMethod);
  });

  // Closing programmatically example
  $('#exampleModal').modal("show");
  setTimeout(function(){
    $('#exampleModal').modal("hide");
  },1000);
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

CodePen