Modal Open Bootstrap 4上的自动对焦输入元件

时间:2018-03-08 16:52:19

标签: input bootstrap-modal bootstrap-4 autofocus

我正在尝试在bootstrap 4模态打开时自动对焦输入元素。我尝试过http://getbootstrap.com/docs/4.0/components/modal/以下的代码,但这不起作用。

有人可以帮助我提供工作演示

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').trigger('focus')
})

1 个答案:

答案 0 :(得分:7)

尝试下面的代码段。也许你需要$(document).ready()



$(document).ready(function() {
  $('#myModal').on('shown.bs.modal', function() {
    $('#myInput').trigger('focus');
  });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />


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

<!-- 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">
        <input type="text" class="form-control" id="myInput">
      </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>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
&#13;
&#13;
&#13;