如何获取聚焦元素与jQuery? [英] How to get the focused element with jQuery?
问题描述
使用jQuery,我如何获得具有插入符号(光标)焦点的输入元素?
Using jQuery, how can I get the input element that has the caret's (cursor's) focus?
或换句话说,如何确定输入是否具有插入符号的焦点?
Or in other words, how to determine if an input has the caret's focus?
推荐答案
// 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文档:
Which one should you use? quoting the jQuery docs:
与其他伪类选择器(以:开头的那些类似),建议在标记名称或其他选择器之前使用focus:focus;否则,通用选择器(*)被隐含。换句话说,裸机
$(':focus')
等效于$('*:focus')
。如果你正在寻找当前焦点元素,$(document.activeElement)将检索它,而不必搜索整个DOM树。
As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare
$(':focus')
is equivalent to$('*:focus')
. If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.
答案是:
document.activeElement
如果你想要一个jQuery对象包装元素:
And if you want a jQuery object wrapping the element:
$(document.activeElement)
这篇关于如何获取聚焦元素与jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!