jQuery 当 div 向下滑动时自动聚焦在输入字段上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12440188/
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-08-26 11:41:11  来源:igfitidea点击:

Autofocus on input field when div slides down

jquerycssinputautofocus

提问by Elmer Almeida

I have is a hidden div. When the button is clicked, the div slides down with an input field. How do I make this input field autofocus as soon as the div slides down? Thanks.

我有一个隐藏的div。单击按钮时,div 会随着输入字段向下滑动。如何在 div 向下滑动后立即使此输入字段自动对焦?谢谢。

<input type="text" name="comment_field" id="comment_field" placeholder="Comment..." />

is what I have and is in a div

是我所拥有的,并且在一个 div 中

$("#status_comments_"+a).slideDown();
    $("#comment_field").focus();

I tried to use the above, but that didn't work.

我尝试使用上面的方法,但是没有用。

回答by undefined

You can use slideDown's callback function which is executed when animation is complete.

您可以使用slideDown在动画完成时执行的回调函数。

$("#status_comments_"+a).slideDown(function(){
    $("#comment_field").focus();
});

Note that IDs must be unique, otherwise your ID selector only selects the first element with that specific ID. If input element is within the div tag you can also code:

请注意,ID 必须是唯一的,否则您的 ID 选择器只会选择具有该特定 ID 的第一个元素。如果输入元素在 div 标签内,您还可以编写代码:

$("#status_comments_"+a).slideDown(function(){
    $('input', this).focus();
});

回答by user5004402

 $("#divId").show().focus();

document.getElementById('divID').focus();

回答by Pranav

hidden field cannot gain focus ..so what you need to do is on click of button you have to show them .

隐藏字段无法获得焦点..所以你需要做的是点击你必须显示的按钮。

$("#status_comments_"+a).show().slideDown();
    $("#comment_field").show().focus();

回答by user5004402

$("#divID").focus();

or without jQuery:

或不使用 jQuery:

document.getElementById('divID').focus();