【问题标题】:How to set focus on first form element in any bootstrap modal如何在任何引导模式中将焦点设置在第一个表单元素上
【发布时间】:2017-07-29 12:03:57
【问题描述】:

我有一个选择下拉列表和 2 个输入字段。我知道如何使用以下方法将焦点设置在任何模式的第一个输入字段上:

$('.modal').on('shown.bs.modal', function () {
  $(this).find('input:text:visible:first').focus();
})

https://www.w3schools.com/code/tryit.asp?filename=FDG195P90CWU

但是当同时存在下拉列表和输入字段时,我看不到该怎么做。

【问题讨论】:

  • 那么当你加载模态框时,你希望选择被聚焦吗?
  • @pasquers 是,但如果它是第一个元素
  • 所以我可能不完全理解要求,但我相信这会做你想要的: .modal-body > select:first, .modal-body > input:first 这样,不管如果如果它是第一个元素,它将被选择,它是一个选择或输入。唯一的要求是它必须是直接孩子
  • @pasquers 我想是的,谢谢,会尝试(我是初学者)
  • this is not actually working when the select isn't present because the input isn't a direct descendant, I'll have to re think through this

标签: javascript jquery css twitter-bootstrap


【解决方案1】:

我想你可能正在寻找这样的东西:$("select:first").focus();

JQuery 代码如下:

$(document).ready(function(){
    $("#myBtn").click(function(){
        $("#myModal").modal();
    });

  $('.modal').on('shown.bs.modal', function () {
    //$(this).find('input:text:visible:first').focus();
    $("select:first").focus();
  })

});

当您运行它时,您可以看到选择框以蓝色突出显示(至少在 Chrome 中是这样)我根据similar question 找到了这个答案。希望有帮助

编辑

如果您希望它选择第一个文本或选择字段,您可以使用:

$(this).find('input[type=text],textarea,select').filter(':visible:first').focus();

如果您需要它来查找其他输入字段(如passwordradio button),您需要将它们添加到find 列表中。另一个similar question asked here

【讨论】:

  • 我认为他们希望选择或输入都被一组样式覆盖
  • @pasquers 尝试过的 crazymatt 解决方案似乎有效,也会尝试您的解决方案
【解决方案2】:

这是@craztmatt 和其他人在此基础上开发的解决方案。我已经扩展为从触发事件的模式开始选择目标元素。

// do this to make bootstrap modals auto-focus.
// delegate to body so that we only have to set it up once.
$('body').on('shown.bs.modal', function (e) {
    var ele = $(e.target).find('input[type=text],textarea,select').filter(':visible:first'); // find the first input on the bs modal
    if (ele) {ele.focus();} // if we found one then set focus.
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2013-07-04
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多