使用jQuery,我怎么能得到有插入符号的(光标的)焦点的输入元素?
或者换句话说,如何确定输入是否具有插入符号的焦点?
$( document.activeElement )
将检索它而不必搜索整个DOM树,如jQuery文档
// 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')等价于$('*:focus')。如果您正在寻找当前关注的元素$(document。activeElement)将检索它,而不必搜索整个DOM树。
$(':focus')
$('*:focus')
答案是:
document.activeElement
如果你想用jQuery对象包装元素:
$(document.activeElement)
试试这个:
$(":focus").each(function() { alert("Focused Elem_id = "+ this.id ); });
我在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.activeElement.id
我使用的是IE8,还没有在其他浏览器上测试过。在我的例子中,我使用它来确保一个字段至少是4个字符,并在执行之前集中。一旦你输入第4个数字,它就会触发。字段的id是'year'。我正在使用..
if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) { // action here }
$(':focus')[0]会给你实际的元素。
$(':focus')[0]
$(':focus')将给你一个元素数组,通常一次只关注一个元素,所以只有当你以某种方式关注多个元素时才会更好。
试试这个::
$(document).on("click",function(){ alert(event.target); });
如果你想确认焦点是否在元素上,那么
if ($('#inputId').is(':focus')) { //your code }