关闭Bootstrap模态框时,注意输入焦点问题。

5

在“bootbox1”输入框上模糊事件后,我想使用Bootstrap Modal来发送消息,当模态框关闭后,焦点应该转移到输入框“bootbox2”,但是输入框没有获得焦点。

我做错了什么?

演示

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();
});
1个回答

15
你需要等待 hidden.bs.modal 事件触发,而不是 hide.bs.modal
根据 Bootstrap 文档hide.bs.modal 事件在调用隐藏方法后立即触发。
hidden.bs.modal 事件会在模态框完成隐藏并等待 CSS 过渡效果结束后触发。
由于在叠层已被移除之前就调用了你的 focus,因此输入框无法获取键盘焦点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接