自动对焦无法在Firefox中以模式形式工作

时间:2019-08-20 16:58:35

标签: javascript bootstrap-4 modal-dialog autofocus

我有一个搜索模式,一旦单击图标,该搜索模式就会弹出,我目前输入的内容为netdata,它在 FF(Firefox)中不起作用。它在 Chrome 中似乎正常运行。我一直在尝试实现各种autofocus="autofocus"来解决此问题,但是没有运气。

任何帮助将不胜感激!

这是我最近尝试过的JS

JS

...并在此之前尝试过此操作

<script type="text/javascript">
    $('#search').on('shown.bs.modal', function() {
        $(this).find('#searchbar').focus();
    });
</script>

没有骰子。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用setTimeout()延迟0毫秒(或另一个较低的值)来触发焦点的设置,方法是检测到事件已显示shown.bs.modal ,例如:

function setFocusOnSearchBar()
{
    $('#searchbar').focus();
}

$("#myModal").on('shown.bs.modal', function()
{
    setTimeout(setFocusOnSearchBar, 0);
});

此方法已在以下位置成功测试

  • Firefox 50.1.0
  • Firefox 68.0.2(64位)
  • Chrome版本60.0.3112.113(正式版)(64位)
  • ChromeVersión76.0.3809.100(正式版)(64位)

完整示例:

function setFocusOnSearchBar()
{
    $('#searchbar').focus();
}

$("#myModal").on('shown.bs.modal', function()
{
    setTimeout(setFocusOnSearchBar, 0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


<div class="container-fluid">
  <h2>Modal Example</h2>

  <!-- Button to Open the Modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
  </button>

  <!-- The Modal -->
  <div class="modal fade" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">

        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Modal Heading</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <!-- Modal body -->
        <div class="modal-body">
          <input id="searchbar" type="text" placeholder="Type to search...">
        </div>

        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
        </div>

      </div>
    </div>
  </div>

</div>