Autofocus on input field when div slides down

2019-03-25 02:42发布

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.

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

is what I have and is in a div

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

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

4条回答
爷的心禁止访问
2楼-- · 2019-03-25 03:23

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();
查看更多
叼着烟拽天下
3楼-- · 2019-03-25 03:24
 $("#divId").show().focus();

document.getElementById('divID').focus();
查看更多
爷、活的狠高调
4楼-- · 2019-03-25 03:28

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

$("#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:

$("#status_comments_"+a).slideDown(function(){
    $('input', this).focus();
});
查看更多
够拽才男人
5楼-- · 2019-03-25 03:36
$("#divID").focus();

or without jQuery:

document.getElementById('divID').focus();
查看更多
登录 后发表回答