使用jQuery,我怎么能得到有插入符号的(光标的)焦点的输入元素?

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


当前回答

$( document.activeElement )

将检索它,而不必搜索整个DOM树,如jQuery文档中推荐的那样

其他回答

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

(1). $(document.activeElement)在Firefox, Chrome和Safari中正常工作。

(2). $(':focus')在Firefox和Safari中正常工作。

我移动到鼠标上输入“name”并按下键盘上的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>

试试这个::

$(document).on("click",function(){
    alert(event.target);
    });

试试这个:

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});
$( document.activeElement )

将检索它,而不必搜索整个DOM树,如jQuery文档中推荐的那样

如果你想确认焦点是否在元素上,那么

if ($('#inputId').is(':focus')) {
    //your code
}