javascript 强制光标进入文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5521139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:28:46  来源:igfitidea点击:

Forcing cursor to go on text field

javascripthtml

提问by David542

How do I make it so when my web page loads, the cursor automatically goes to a given text field? (For example, on Google when you load the page, the blinking cursor is already on the search box)

如何在我的网页加载时使光标自动转到给定的文本字段?(例如,在 Google 上加载页面时,闪烁的光标已经在搜索框上)

回答by bradley.ayers

You need to use JavaScript. e.g.

您需要使用 JavaScript。例如

<input type="text" id="search" />
<script type="text/javascript">
document.getElementById('search').focus()
</script>

回答by Tim Down

Be careful implementing this functionality. It's very annoying for a user to focus on a field and start typing only to find the caret has been redirected while typing when the page finished loading. I've seen this happen on numerous sites.

小心实现此功能。对于用户来说,专注于一个字段并开始输入却发现在页面加载完成后输入时插入符号已被重定向是非常烦人的。我在很多网站上都看到过这种情况。

I'd suggest using the HTML5 autofocusattribute and falling back to a JavaScript solution in browsers which don't support it. The following gets round the above problem by not waiting for the document to load before setting the focus:

我建议autofocus在不支持它的浏览器中使用 HTML5属性并回退到 JavaScript 解决方案。以下通过在设置焦点之前不等待文档加载来解决上述问题:

<input type="text" name="search" id="search" autofocus>
<script type="text/javascript">
    var input = document.getElementById("search");
    if ( !("autofocus" in input) ) {
        input.focus();
    }
</script>

More information can be found at diveintohtml.org: http://diveintohtml5.ep.io/forms.html#autofocus

更多信息可以在diveintohtml.org上找到:http: //diveintohtml5.ep.io/forms.html#autofocus

回答by Bala R

Try

尝试

<body onLoad="document.form1.txtBox1.focus()">

回答by nicorellius

Since HTML5 is in full force, I believe autofocusis well supported. I would take heed to the other answers here, but in my opinion, much easier than JavaScript:

由于 HTML5 已全面生效,我相信autofocus它得到了很好的支持。我会注意这里的其他答案,但在我看来,比 JavaScript 容易得多:

<input type="text" name="name" autofocus>