如何将焦点设置为独立于 id 的 HTML 表单中的第一个输入元素?

问题描述 投票:0回答:19

是否有一种简单的方法可以在加载页面时设置网页的焦点(输入光标)在第一个输入元素(文本框、下拉列表等)上,而无需知道元素的ID?

我想将其实现为我的 Web 应用程序的所有页面/表单的通用脚本。

javascript html forms focus
19个回答
158
投票

虽然这并不能回答问题(需要通用脚本),但我认为让其他人知道 HTML5 引入了“autofocus”属性可能会很有用:

<form>
  <input type="text" name="username" autofocus>
  <input type="password" name="password">
  <input type="submit" value="Login">
</form>

深入了解 HTML5 了解更多信息。


104
投票

您也可以尝试基于 jQuery 的方法:

$(document).ready(function() {
    $('form:first *:input[type!=hidden]:first').focus();
});

42
投票
document.forms[0].elements[0].focus();

这可以使用循环来细化,例如。不关注某些类型的字段、禁用的字段等。更好的方法可能是将 class="autofocus" 添加到您实际do想要聚焦的字段,然后循环遍历 forms[i].elements[j] 寻找该 className。

无论如何:在每个页面上都这样做通常不是一个好主意。当您集中输入时,用户将失去例如的能力。通过键盘滚动页面。如果出现意外,这可能会很烦人,因此只有当您非常确定使用表单字段将是用户想要执行的操作时才自动聚焦。 IE。如果你是谷歌。


21
投票

我发现最全面的 jQuery 表达式是(通过 here 的帮助)

$(document).ready(function() {
    $('input:visible:enabled:first').focus();
});

11
投票

我需要为在我的页面上的模态 div 中动态显示的表单解决这个问题,不幸的是,当通过更改

autofocus
属性显示包含的 div 时,
display
不会得到满足(至少在铬合金)。我不喜欢任何需要我的代码来推断我应该将焦点设置为哪个控件的解决方案,因为隐藏或零大小的输入等很复杂。我的解决方案是在我的控件上设置
autofocus
属性无论如何输入,然后在显示 div 时在代码中设置焦点:

form.querySelector('*[autofocus]').focus();

7
投票

如果您使用 Prototype JavaScript 框架,那么您可以使用 focusFirstElement 方法:

Form.focusFirstElement(document.forms[0]);

6
投票

这里有一篇文章可能有用:将焦点设置为网页上的第一个输入


5
投票

您还需要跳过任何隐藏的输入。

for (var i = 0; document.forms[0].elements[i].type == 'hidden'; i++);
document.forms[0].elements[i].focus();

4
投票

将此代码放在

body
标签的末尾将自动将第一个可见的、非隐藏的启用元素聚焦在屏幕上。它将处理我能在短时间内想到的大多数情况。

<script>
    (function(){
        var forms = document.forms || [];
        for(var i = 0; i < forms.length; i++){
            for(var j = 0; j < forms[i].length; j++){
                if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                    forms[i][j].focus();
                    return;
                }
            }
        }
    })();
</script>

4
投票

我正在用这个:

$("form:first *:input,select,textarea").filter(":not([readonly='readonly']):not([disabled='disabled']):not([type='hidden'])").first().focus();

3
投票

尝试了上面的很多答案,但都不起作用。找到这个:http://www.kolodvor.net/2008/01/17/set-focus-on-first-field-with-jquery/#comment-1317 谢谢科洛德沃。

$("input:text:visible:first").focus();

3
投票

没有jquery,例如使用常规 javascript:

document.querySelector('form input:not([type=hidden])').focus()

适用于 Safari,但不适用于 Chrome 75(2019 年 4 月)


2
投票

这将获取任何可见的公共输入中的第一个,包括文本区域和选择框。这也确保它们不会被隐藏、禁用或只读。它还允许使用我在软件中使用的目标 div(即,此表单内的第一个输入)。

$("input:visible:enabled:not([readonly]),textarea:visible:enabled:not([readonly]),select:visible:enabled:not([readonly])", 
    target).first().focus();

1
投票

对于那些使用 JSF2.2+ 并且无法将 autofocus 作为没有值的属性传递的人,请使用:

 p:autofocus="true"

并将其添加到命名空间 p (也经常使用 pt。无论你喜欢什么)。

<html ... xmlns:p="http://java.sun.com/jsf/passthrough">

0
投票

AngularJS

angular.element('#Element')[0].focus();

0
投票

这包括文本区域,不包括单选按钮

$(document).ready(function() {
    var first_input = $('input[type=text]:visible:enabled:first, textarea:visible:enabled:first')[0];
    if(first_input != undefined){ first_input.focus(); }
});

0
投票

您应该能够使用 clientHeight 而不是检查显示属性,因为父级可能会隐藏此元素:

function setFocus() {
    var forms = document.forms || [];
        for (var i = 0; i < forms.length; i++) {
            for (var j = 0; j < forms[i].length; j++) {
            var widget = forms[i][j];
                if ((widget && widget.domNode && widget.domNode.clientHeight > 0) && typeof widget.focus === "function")
                 && (typeof widget.disabled === "undefined" || widget.disabled === false)
                 && (typeof widget.readOnly === "undefined" || widget.readOnly === false)) {
                        widget.focus();
                        break;
                }
            }
        }
    }   
}

0
投票

如果没有第三方库,请使用类似的东西

  const inputElements = parentElement.getElementsByTagName('input')
  if (inputChilds.length > 0) {
    inputChilds.item(0).focus();
  }

确保考虑所有表单元素标签,排除隐藏/禁用的标签,如其他答案等..


0
投票

这是最适合我的 jQuery 代码。

$("form").find('input, textarea').first().focus();

我为第一个表单输入元素是文本区域的可能事件添加了文本区域。

© www.soinside.com 2019 - 2024. All rights reserved.