最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Forcing cursor to go on text field - Stack Overflow

programmeradmin5浏览0评论

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)

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)

Share Improve this question edited Apr 2, 2011 at 4:31 bradley.ayers 38.4k14 gold badges98 silver badges101 bronze badges asked Apr 2, 2011 at 4:24 David542David542 110k203 gold badges564 silver badges1k bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

You need to use JavaScript. e.g.

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

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 autofocus attribute 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:

<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

Try

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

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

<input type="text" name="name" autofocus>
发布评论

评论列表(0)

  1. 暂无评论