JavaScript将焦点设置为HTML表单元素

本文翻译自:JavaScript set focus to HTML form element

I have a web form with a text box in it. 我有一个带有文本框的Web表单。 How do I go about setting focus to the text box by default? 如何默认将焦点设置到文本框?

Something like this: 像这样的东西:

<body onload='setFocusToTextBox()'>

so can anybody help me with it? 所以有人可以帮我吗? I don't know how to set focus to the text box with JavaScript. 我不知道如何使用JavaScript将焦点设置到文本框。

<script>
function setFocusToTextBox(){
//What to do here
}
</script>

#1楼

参考:https://stackoom.com/question/1BQjQ/JavaScript将焦点设置为HTML表单元素


#2楼

Do this. 做这个。

If your element is something like this.. 如果你的元素是这样的..

<input type="text" id="mytext"/>

Your script would be 你的脚本会是

<script>
function setFocusToTextBox(){
    document.getElementById("mytext").focus();
}
</script>

#3楼

For plain Javascript, try the following: 对于普通Javascript,请尝试以下操作:

window.onload = function() {
  document.getElementById("TextBoxName").focus();
};

#4楼

Usually when we focus on a textbox, we should also scroll into view 通常当我们关注文本框时,我们也应该滚动到视图中

function setFocusToTextBox(){
    var textbox = document.getElementById("yourtextbox");
    textbox.focus();
    textbox.scrollIntoView();
}

Check if it helps. 检查它是否有帮助。


#5楼

For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. 对于它的价值,您可以在兼容HTML5的浏览器上使用autofocus属性。 Works even on IE as of version 10. 从版本10开始,甚至可以在IE上运行。

<input name="myinput" value="whatever" autofocus />

#6楼

As mentioned earlier, document.forms works too. 如前所述, document.forms也有效。

function setFocusToTextBox( _element ) {
  document.forms[ 'myFormName' ].elements[ _element ].focus();
}

setFocusToTextBox( 0 );
// sets focus on first element of the form
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值