Javascript 如何使用 jQuery 获取焦点元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11277989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:15:00  来源:igfitidea点击:

How to get the focused element with jQuery?

javascriptjquerycursorelementcaret

提问by dave

Using jQuery, how can I get the input element that has the caret's (cursor's) focus?

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

Or in other words, how to determine if an input has the caret's focus?

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

回答by gdoron is supporting Monica

// 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;

Which one should you use? quoting the jQuery docs:

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

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.

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

The answer is:

答案是:

document.activeElement

And if you want a jQuery object wrapping the element:

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

$(document.activeElement)

回答by Grilse

$( document.activeElement )

Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation

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

回答by ucdream

I've tested two ways in Firefox, Chrome, IE9 and Safari.

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

(1). $(document.activeElement)works as expected in Firefox, Chrome and Safari.

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

(2). $(':focus')works as expected in Firefox and Safari.

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

I moved into the mouse to input 'name' and pressed Enter on keyboard, then I tried to get the focused element.

我移入鼠标输入“名称”并按键盘上的 Enter 键,然后尝试获取焦点元素。

(1). $(document.activeElement)returns the input:text:name as expected in Firefox, Chrome and Safari, but it returns input:submit:addPassword in IE9

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

(2). $(':focus')returns input:text:name as expected in Firefox and Safari, but nothing in IE

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

回答by Adil Malik

Try this:

尝试这个:

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

回答by Sparky aka tom

How is it noone has mentioned..

怎么没人提。。

document.activeElement.id

I am using IE8, and have not tested it on any other browser. In my case, I am using it to make sure a field is a minimum of 4 characters and focused before acting. Once you enter the 4th number, it triggers. The field has an id of 'year'. I am using..

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

if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
    // action here
}

回答by Travis Heeter

$(':focus')[0]will give you the actual element.

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

$(':focus')will give you an array of elements, usually only one element is focused at a time so this is only better if you somehow have multiple elements focused.

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

回答by Pudugurthi Ravindar

Try this::

尝试这个::

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

回答by Sandeep Singh

If you want to confirm if focus is with an element then

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

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