首页 > 解决方案 > Bootstrap modal 将焦点放在靠近正文输入的弹出窗口上

问题描述

嗨堆栈溢出社区的人

当用户单击引导模式窗口时,我想将焦点设置在输入上。

我尝试了下面的代码但没有帮助。任何帮助表示赞赏

$('#myModal').on('hidden.bs.modal', function() {
  $('#focusMe').focus()
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">

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

<label>Foucs Me</label>
<input type="text" id="focusMe">

<!-- Modal -->
<div class="modal fade" id="myModal" 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>
<!-- JS code -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js">
</script>

标签: javascriptjquerybootstrap-4bootstrap-modalsetfocus

解决方案


您只需要setTimeout()在调用 focus() 事件进行输入之前添加函数。

focus()在引导模式关闭后立即调用的代码方法中,当DOM未正确加载时。

$('#myModal').on('hidden.bs.modal', function() {
  setTimeout(function(){
      $('#focusMe').focus();
  },100);
});

推荐阅读