首页 > 解决方案 > 在 Bootstrap 中触发模态隐藏时是否可以停止模态隐藏?

问题描述

在引导程序中,当点击关闭按钮或背景时,是否可以停止模态隐藏?

例如,如果我运行一个语句来检查真假。如果为假,我可以停止模态隐藏吗?

$(document).on('hide.bs.modal', '#test-modal', function(e) {

  var confirm = confirm("Sure you wanna close this modal?");

  if (confirm == true) {

    // i'm sure, continue closing the modal

  } else {

    // halt closing this modal

  } 

});

这里有一个小提琴准备测试......

https://jsfiddle.net/joshmoto/yc340rpd/

标签: javascriptjquerybootstrap-4

解决方案


您可以简单地使用e.preventDefaultinhide.bs.modal来防止模式关闭。另外,请注意这confirm是一个窗口对象,因此您可能应该选择不同的变量名称以避免这种情况。

请参阅概念验证示例:

$('#test-modal').modal('show');

$(document).on('hide.bs.modal', '#test-modal', function(e) {

  var shouldCloseModal = confirm("Sure you wanna close this modal?");

  if (!shouldCloseModal) {
    e.preventDefault();
  } 

});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>

<div class="modal fade" id="test-modal" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Test Modal</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">

        Try close me and then stop me! If you can...

      </div>

    </form>
  </div>
</div>


推荐阅读