在twitter bootstrap模式中自动对焦输入

eaw*_*wer 48 jquery modal-dialog twitter-bootstrap

我有这样的问题 - 我需要在twitter bootstrap模式中自动聚焦一些元素(在它显示之后).棘手的部分在这里 - 这个模态的内容是使用'data-remote'(jQuery.load方法)从单独的HTML文件加载的,所以

$(document).on('shown', ".modal", function() {
    $('[autofocus]', this).focus();
});
Run Code Online (Sandbox Code Playgroud)

仅在之前加载模态时才有效.
问题是 - 如何在第一次模态加载时使自动对焦工作?

nc.*_*nc. 101

我正在使用Bootstrap 3.0(希望这也适用于3.1).

我们不得不使用tabindex="-1"因为它允许ESC键关闭模态.

所以我能够使用以下方法修复此问题:

// Every time a modal is shown, if it has an autofocus element, focus on it.
$('.modal').on('shown.bs.modal', function() {
  $(this).find('[autofocus]').focus();
});
Run Code Online (Sandbox Code Playgroud)

  • 这是3.0及以上的答案 (3认同)

小智 26

尝试删除tabindex =" - 1",它工作正常.

<div class="modal fade" id="modalID" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

<div class="modal fade" id="modalID" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 当我删除`tabindex =" - 1"`时,可以跳出并激活模态外的按钮.解决方案由nc提供.为我工作. (2认同)
  • 嗨,只想仔细检查一下这个解决方案,我试试这个,它只能工作一次.你有没有注意到那一个?然后我尝试@nc.回答它甚至与`tabindex =" - 1"`完美配合 (2认同)

Pau*_*ver 17

我无法让@ nc的解决方案在我的应用程序上工作.它没有看到后来添加的模态.这虽然对我有用

$(document).on('shown.bs.modal', '.modal', function() {
  $(this).find('[autofocus]').focus();
});
Run Code Online (Sandbox Code Playgroud)

正如Frank Fang指出的那样,如果您使用的是不依赖于autofocusHTML属性的较新版本的Bootstrap,则应使用此方法.

$('#myModal').on('shown.bs.modal', function () {
  // get the locator for an input in your modal. Here I'm focusing on
  // the element with the id of myInput
  $('#myInput').focus()
})
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是我用于JS首次运行时DOM中不存在的模态的解决方案. (3认同)

小智 6

对于最新的 Bootstrap 版本,上述答案有些过时。

以下摘录自: http: //getbootstrap.com/javascript/#modals

由于 HTML5 定义其语义的方式,autofocusHTML 属性在 Bootstrap 模式中不起作用。要达到相同的效果,请使用一些自定义 JavaScript:

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
})
Run Code Online (Sandbox Code Playgroud)