如何使用jQuery使HTML元素获得焦点

14

如何使用jQuery将焦点聚焦在HTML元素上

6个回答

31

相当容易。

$('#itemId').focus();

4

我希望您在6年前就能找到这个问题,但如果您在当前的Firefox和Chrome上打开控制台工具并测试焦点功能,可能会导致焦点事件无法正确触发。

为了测试它,您可以使用setTimeout,在它触发之前关闭开发者工具。

例如:

setTimeout(focusAtMyElement, 3000);

function focusAtMyElement(){
    $('#my-element').focus();
}

我并不建议在生产代码中使用setTimeout,这只是为了“视觉测试目的”,以便在焦点事件触发之前可以关闭浏览器上的开发工具并查看预期结果。


1
在尝试了一个小时的所有可能性后,这才解决了问题!focus() 的实际功能完全正常 - 只是无法通过控制台手动执行! - Brian Powell

2
您可以通过元素类型、ID或类来进行聚焦。例如,创建一个按钮。
> <button id="id" class="class1">

现在,要将焦点放在这个按钮上,您可以按照以下方法操作: 1.通过按钮本身。注意:如果有多个按钮,则会聚焦于最后一个按钮。 $("button").focus();
2.通过类名进行聚焦(在类名前使用“.”)。 $(".class1").focus();
3.通过其ID进行聚焦(在ID前使用“#”)。 $("#id").focus();
4.甚至可以通过按钮后跟其类名来聚焦。 $("button.class1").focus();

2
$("input").focus();

这就是你需要的!


1
<input class="element_class" type="text"/>
<input id="element_id" type="text"/>

<script>
    $('.element_class').focus();
    // the following will obviously blur() the previous
    $('#element_id').focus();
</script>

聚焦文档
模糊文档


0

HTML:

<form>
  <input id="target" type="text" value="Field 1" />
  <input type="text" value="Field 2" />
</form>
<div id="other">
  Trigger the handler
</div>

重点示例

$('#target').focus(function() {
  alert('Handler for .focus() called.');
});


$('#other').click(function() {
  $('#target').focus();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接