【问题标题】:Focus on Input when Bootstrap Modal closesBootstrap Modal 关闭时关注输入
【发布时间】:2018-01-31 16:52:13
【问题描述】:

在输入字段“bootbox1”上发生模糊事件后,我想使用 Bootstrap 模态消息,在模态关闭后焦点将转到输入字段“bootbox2”。但是输入字段没有获得焦点。

我做错了什么?

Demo

HTML

<input type="text" id="bootbox" />
<input type="text" id="bootbox2" />
<div id="myModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
        <!-- dialog body -->
        <div class="modal-body">
            <button type="button" class="close" data-dismiss="modal">&times;</button>Hello world!</div>
        <!-- dialog buttons -->
        <div class="modal-footer">
            <button type="button" class="btn btn-primary">OK</button>
        </div>
    </div>
  </div>
</div>

JS

$('#bootbox').on('blur', function checkSelection(e) {
  $("#myModal").on("show", function () { // wire up the OK button to dismiss the modal when shown
    $("#myModal a.btn").on("click", function (e) {
        console.log("button pressed"); // just as an example...
        $("#myModal").modal('hide');
        $('#bootbox2').focus();
        // dismiss the dialog
    });
  });

  $("#myModal").on("hide", function () { // remove the event listeners when the dialog is dismissed
    $("#myModal a.btn").off("click");
    $('#bootbox2').focus();
  });

  $("#myModal").on("hidden", function () { // remove the actual elements from the DOM when fully hidden
    $("#myModal").remove();
  });

  $("#myModal").modal({ // wire up the actual modal functionality and show the dialog
    "backdrop": "static",
        "keyboard": true,
        "show": true // ensure the modal is shown immediately
  });

});

//this works
$('#bootbox2').on('blur', function checkSelection(e) {
  $('#bootbox').focus();
});

【问题讨论】:

    标签: javascript jquery twitter-bootstrap focus


    【解决方案1】:

    您需要等待hidden.bs.modal 事件触发,而不是hide.bs.modal。

    根据Bootstrap Docs事件hide.bs.modal

    当隐藏实例方法已经被触发时,该事件立即被触发 调用。

    而hidden.bs.modal

    当模态框从 用户(将等待 CSS 转换完成)​​。

    由于您的 focus 在覆盖层被移除之前被调用,因此输入还不能获得键盘焦点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-04
      • 2014-02-09
      • 2017-11-28
      • 2019-08-26
      • 2021-04-06
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      相关资源
      最近更新 更多