![](/img/trans.png)
[英]How can I set the focus to a certain element in a form using JavaScript?
[英]How can I set focus on an element in an HTML form using JavaScript?
我有一个 web 表单,里面有一个文本框。 go 如何将焦点默认设置到文本框?
是这样的:
<body onload='setFocusToTextBox()'>
所以有人可以帮我吗? 我不知道如何使用 JavaScript 将焦点设置到文本框。
<script>
function setFocusToTextBox(){
//What to do here
}
</script>
做这个。
如果你的元素是这样的..
<input type="text" id="mytext"/>
你的脚本将是
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
对于它的价值,您可以在 HTML5 兼容浏览器上使用autofocus
属性。 从版本 10 开始,甚至可以在 IE 上运行。
<input name="myinput" value="whatever" autofocus />
通常当我们关注一个文本框时,我们也应该滚动到视图中
function setFocusToTextBox(){
var textbox = document.getElementById("yourtextbox");
textbox.focus();
textbox.scrollIntoView();
}
检查它是否有帮助。
如果您的代码是:
<input type="text" id="mytext"/>
如果您使用的是 JQuery,您也可以使用它:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
请记住,您必须先绘制输入$(document).ready()
对于普通的 Javascript,请尝试以下操作:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
我曾经只是使用这个:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
也就是说,您可以在 HTML 5 中使用 autofocus 属性。
请注意:我想更新这个旧线程,显示所询问的示例,以及为仍在阅读本文的人提供更新、更简单的更新。 ;)
如前所述, document.forms 也能工作。
function setFocusToTextBox( _element ) {
document.forms[ 'myFormName' ].elements[ _element ].focus();
}
setFocusToTextBox( 0 );
// sets focus on first element of the form
如果您的<input>
或<textarea>
具有属性id=mytext
然后使用
mytext.focus();
function setFocusToTextBox() { mytext.focus(); }
<body onload='setFocusToTextBox()'> <form> <input type="text" id="mytext"/> </form> </body>
这个例子对我有用
$(document).ready(function () {
document.getElementById('TextBox').focus();
}
window.onload 最初是将焦点放在 onblur 是在您单击文本区域外时将焦点放在焦点上,或者避免文本区域模糊
<textarea id="focus"></textarea>
<script>
var mytexarea=document.getElementById("focus");
window.onload=function()
{
mytexarea.focus();
}
</script>
试试这个:
$('.modal').on('shown.bs.modal', function () {
setTimeout(function() {
$("input#yourFieldId").addClass('modal-primary-focus').focus();
},
500);
});
想分享这个主题的一些边缘案例。 如果您的内容正在重新加载(示例来自 API 的动态 DOM 加载结果并将焦点设置在结果的第一项上)添加属性autofocus将不是您的解决方案,它仅适用于第一次加载,第二次 DOM 更改将不起作用但在 static DOM 中工作正常或单页加载。 如果你有动态组件加载数据,简单的.focus()将失败,因为在 focus() 尚未创建时触发对元素的关注,或者 blur 尚未由 DOM 完成。 对于这种情况,预期的是添加延迟时间(setTimeout 函数),以便为焦点提供时间以应用于 DOM 中新创建或重新创建的元素。 我的案例是从 API 加载数据并关注第一个结果。 添加var el = document.getElementById(focusId); el.focus();
var el = document.getElementById(focusId); el.focus();
解决了这个问题,因此 DOM 可以在不增加延迟的情况下完成模糊。
<input type="text" class="word"> //html code
let theinput = document.querySelector(".word"); //Get the input
theinput.focus(); // focus on input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.