有条件地防止Bootstrap 4模态关闭" esc"

时间:2018-01-18 15:24:25

标签: javascript twitter-bootstrap bootstrap-4

我在第一次加载页面时使用会话存储来显示和隐藏模态。我不知道如何使用cookies,所以我只使用会话存储。

在模态中,我在第一次关闭它时更改标题和关闭按钮,然后可以作为"帮助模式"而不是"开始"。

如果未设置会话存储且处于"开始使用"我想阻止使用esc关闭模式模式,但当你关闭模态并重新打开它作为"帮助模式"启用esc事件。

目前我的工作时间为50%,第一次无法使用esc,但如果您将其作为"帮助"您仍然无法使用esc,但是,如果您重新加载页面esc它可以使用,

以下是我的代码的else部分,在未设置会话存储时有效:

} else {
  // show the help modal
  $('#help').modal({
    keyboard: false
  });

  $('#help').modal('show');

  $('#help').on('hidden.bs.modal', function (e) {
    keyboard: true
  })
}

文档(https://getbootstrap.com/docs/4.0/components/modal/#events) 表示当模态完成对用户的隐藏时会触发.on('hidden.bs.modal'事件。

我必须使用哪个事件才能使其正常工作?

1 个答案:

答案 0 :(得分:1)

看起来,你不能简单地通过向它提供新的options对象来重新配置已经初始化的模态。这意味着如果您执行以下操作:

$('#help').modal({
    keyboard: false
});

$('#help').modal({
    keyboard: true
});

...比后者的声明没有任何效果。 所以,为了克服这个问题,我建议销毁第一个模态 - 带有keyboard: false的模态 - 并创建一个新的模态来监听键盘事件。

检查下面的工作代码段 注意:第一个模态是在使用keyboard: false的代码的pageload中创建的,而按钮启动的连续模式是使用默认值设置的,因此使用keyboard: true



// } else {
    // show the help modal
    $('#help').modal({
        keyboard: false
    });

    // Note the `one` binding
    $('#help').one('hidden.bs.modal', function (event) {
        $('#help').modal('dispose');
    });
// }

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#help">
    Open Help
</button>


<div id="help" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">HELP</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>This is the Help modal</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
&#13;
&#13;
&#13;

相关问题