div 向下滑动时自动对焦于输入字段



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

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

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

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

我尝试使用上述方法,但没有奏效。

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

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

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

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

或者没有jQuery:

document.getElementById('divID').focus();
 $("#divId").show().focus();
document.getElementById('divID').focus();

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

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

最新更新