简体   繁体   English

jQuery:当浏览器未聚焦时聚焦

[英]JQuery :focus when the browser ain't focused

Without considering the performance, I always tough the jquery object returned by $(":focus") would be equivalent to $(document.activeElement) . 在不考虑性能的情况下,我总是坚韧地将$(":focus")返回的jquery对象等同于$(document.activeElement)

However, if you're breaking into browser debugger and evaluate $(":focus") , you won't get any element while $(document.activeElement) will still return the focused element. 但是,如果您要进入浏览器调试器并评估$(":focus") ,则您将不会获得任何元素,而$(document.activeElement)仍将返回聚焦的元素。 I was thinking about some kind of observer effect issue but the same is also true if you set the focus outside the browser. 我正在考虑某种观察者效果问题,但是如果将焦点设置在浏览器之外,情况也是如此。

According to jquery documentation , the focus selector should " Selects element if it is currently focused ". 根据jquery文档 ,焦点选择器应“ 如果当前已焦点,则选择元素 ”。 As there's no mention about the browser focus, I was wondering if this was the expected behaviour or if it should be reported as a bug. 由于没有提及浏览器焦点,因此我想知道这是否是预期的行为,还是应该将其报告为错误。

If you want to try this behaviour, I created a JsFiddle example. 如果您想尝试这种行为,我创建了一个JsFiddle示例。 You'll see text how $(":focus") reacts when you'll focus away from the input (within the form, in the console or in an other application). 您将看到文本,当您将焦点从输入移开(在表单中,在控制台中或在其他应用程序中)时, $(":focus")会如何反应。

Take a look at the source for the :focus selector: 看一下:focus选择器的源代码:

"focus": function( elem ) {
    return elem === document.activeElement
        && (!document.hasFocus || document.hasFocus()) 
        && !!(elem.type || elem.href || ~elem.tabIndex);
}

So in order for the element to be returned, elem must equal the document.activeElement , the document must have focus, and the element must have a type , href , or tabIndex property. 因此,为了返回元素, elem必须等于document.activeElement ,文档必须具有焦点,并且元素必须具有typehreftabIndex属性。

The two are not equivalent 两者不相等


edit 编辑

In your fiddle when you remove focus from the input, document.activeElement becomes the body , and it doesn't matter whether or not the document has focus. 当您从输入中删除焦点时, document.activeElement会成为body ,并且文档是否具有焦点也无关紧要。

As you can see here CSS :focus Selector 如您在这里看到的CSS:focus Selector

The :focus selector is allowed on elements that accept keyboard events or other user inputs. :focus选择器可用于接受键盘事件或其他用户输入的元素。

And document.activeElement can contain any or almost any element from the page 并且document.activeElement可以包含页面中的任何或几乎任何元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM