378

使用 jQuery,如何获取具有插入符号(光标)焦点的输入元素?

或者换句话说,如何确定输入是否具有插入符号的焦点?

4

8 回答 8

797
// Get the focused element:
var $focused = $(':focus');

// No jQuery:
var focused = document.activeElement;

// Does the element have focus:
var hasFocus = $('foo').is(':focus');

// No jQuery:
elem === elem.ownerDocument.activeElement;

你应该使用哪一个?引用jQuery 文档

与其他伪类选择器(以“:”开头的选择器)一样,建议在 :focus 前面加上标签名称或其他选择器;否则,将隐含通用选择器 ("*")。换句话说,bare$(':focus')等价于$('*:focus'). 如果您正在寻找当前聚焦的元素,$( document.activeElement ) 将检索它而无需搜索整个 DOM 树。

答案是:

document.activeElement

如果你想要一个包装元素的 jQuery 对象:

$(document.activeElement)
于 2012-06-30T21:57:55.653 回答
38
$( document.activeElement )

无需按照jQuery 文档中的建议搜索整个 DOM 树即可检索它

于 2012-06-30T21:57:52.110 回答
6

我在 Firefox、Chrome、IE9 和 Safari 中测试了两种方法。

(1)。$(document.activeElement)在 Firefox、Chrome 和 Safari 中按预期工作。

(2)。$(':focus')在 Firefox 和 Safari 中按预期工作。

我移动到鼠标中输入“名称”并在键盘上按 Enter,然后我试图获得焦点元素。

(1)。$(document.activeElement)在 Firefox、Chrome 和 Safari 中按预期返回 input:text:name,但在 IE9 中返回 input:submit:addPassword

(2)。$(':focus')在 Firefox 和 Safari 中按预期返回 input:text:name,但在 IE 中没有

<form action="">
    <div id="block-1" class="border">
        <h4>block-1</h4>
        <input type="text" value="enter name here" name="name"/>            
        <input type="button" value="Add name" name="addName"/>
    </div>
    <div id="block-2" class="border">
        <h4>block-2</h4>
        <input type="text" value="enter password here" name="password"/>            
        <input type="submit" value="Add password" name="addPassword"/>
    </div>
</form>
于 2013-05-20T15:24:51.950 回答
5

试试这个:

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});
于 2012-06-30T22:00:19.047 回答
2

怎么没人提。。

document.activeElement.id

我使用的是 IE8,还没有在任何其他浏览器上测试过。在我的例子中,我使用它来确保一个字段至少有 4 个字符,并且在行动之前集中注意力。一旦你输入第四个数字,它就会触发。该字段的 id 为“年份”。我在用..

if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
    // action here
}
于 2018-01-08T02:45:54.413 回答
1

$(':focus')[0]会给你实际的元素。

$(':focus')会给你一个元素数组,通常一次只关注一个元素,所以如果你以某种方式关注多个元素,这只会更好。

于 2018-07-06T14:38:09.700 回答
1

试试这个::

$(document).on("click",function(){
    alert(event.target);
    });
于 2018-12-20T08:21:56.673 回答
1

如果您想确认焦点是否与元素有关,那么

if ($('#inputId').is(':focus')) {
    //your code
}
于 2020-04-14T15:32:51.397 回答