简体   繁体   English

如何使用JavaScript将焦点设置为表单中的某个元素?

[英]How can I set the focus to a certain element in a form using JavaScript?

My page has a form that has a text field in it. 我的页面的表单中包含文本字段。 I'd like to set the focus to that text field as soon as the page loads, so that users do not have to click it to start typing. 我想在页面加载后立即将焦点设置到该文本字段,以便用户不必单击它即可开始键入。 How can I do this? 我怎样才能做到这一点?

Use the focus() method on the object. 在对象上使用focus()方法。

For example: 例如:

document.getElementById("something").focus();
...
<input type='text' id='something' />

you have to select your element first and then focus it by using focus() :P 您必须先选择元素,然后使用focus()来聚焦它:P

function hokusfocus(e)
{
  var fokus = document.getElementById(e);
  fokus.focus();
}

onload = hokusfocus("yourId"); /* makes sure your document is loaded before the focus */

您尝试使用谷歌搜索吗?

document.getElementById("textboxId").focus();

use autofocus attribute like this: 使用如下的自动对焦属性:

<html>
<head>

</head>
<body>
<dl>
<dt><label>username:</label><dt>
<dd><input type="text" autofocus></dd>

<dt><label>password:</label><dt>
<dd><input type="password"></dd>

</dl>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM