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

使用jQuery,我怎样才能得到插入符(游标)焦点的input元素?

或换句话说,如何确定一个input是否有脱字符的焦点?

// 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文档 :

与其他伪类select器(以“:”开头的那些)类似,build议先执行:使用标记名称或其他select器进行聚焦; 否则,暗示通用select器(“*”)。 换句话说,裸$(':focus')等价于$('*:focus') 。 如果您正在查找当前的焦点元素,$(document.activeElement)将检索它,而不必search整个DOM树。

答案是:

 document.activeElement 

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

 $(document.activeElement) 
 $( document.activeElement ) 

将检索它,而不必像在jQuery文档中推荐的一样search整个DOM树

尝试这个:

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

我已经testing了Firefox,Chrome,IE9和Safari两种方式。

(1)。 $(document.activeElement)按照预期在Firefox,Chrome和Safari中运行。

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

我移动到鼠标input“名称”,并按下键盘上的回车,然后我试图获得聚焦的元素。

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

(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>