I would like to find out, in Javascript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how?
我想在Javascript中找出当前关注的元素。我一直在DOM中寻找,但是还没有找到我需要的东西。有办法做到这一点吗?
The reason I was looking for this:
我寻找这个的原因是:
I'm trying to make keys like the arrows and enter
navigate through a table of input elements. Tab works now, but enter and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.
我试着在输入元素的表格中创建像箭头这样的键并输入导航。选项卡现在可以工作了,但是输入和箭头在默认情况下似乎不工作。我已经设置了关键的处理部分,但是现在我需要弄清楚如何在事件处理函数中移动焦点。
17 个解决方案
#1
1192
Use document.activeElement
, it is supported in all major browsers.
使用文档。activeElement在所有主流浏览器中都支持。
Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.
在此之前,如果您试图找出什么表单字段具有焦点,您就不能。要在旧的浏览器中模拟检测,请向所有字段添加“焦点”事件处理程序,并在一个变量中记录最后聚焦的字段。添加一个“blur”处理程序,清除最后焦点字段的blur事件中的变量。
Related links:
相关链接:
- activeElement Browser Compatibility
- activeElement浏览器兼容性
- jQuery alternative for document.activeElement
- jQuery选择document.activeElement
#2
106
As said by JW, you can't find the current focused element, at least in a browser-independent way. But if your app is IE only (some are...), you can find it the following way :
正如JW所说,您无法找到当前的焦点元素,至少是在浏览器独立的方式中。但如果你的应用程序是IE(有些是…),你可以通过以下方式找到:
document.activeElement
EDIT: It looks like IE did not have everything wrong after all, this is part of HTML5 draft and seems to be supported by the latest version of Chrome, Safari and Firefox at least.
编辑:看起来IE并没有什么问题,这是HTML5草案的一部分,并且至少支持最新版本的Chrome、Safari和Firefox。
#3
76
If you can use jQuery, it now supports :focus, just make sure you are using version 1.6+.
如果您可以使用jQuery,它现在支持:focus,请确保您使用的是1.6+版本。
This statement will get you the currently focused element.
此语句将为您提供当前关注的元素。
$(":focus")
From: How to select an element that has focus on it with jQuery
From: How to select a element that has focus on it with jQuery
#4
38
document.activeElement
is now part of the HTML5 working draft specification, but it might not yet be supported in some non-major/mobile/older browsers. You can fall back to querySelector
(if that is supported). It's also worth mentioning that document.activeElement
will return document.body
if no element is focused — even if the browser window doesn't have focus.
文档。activeElement现在是HTML5工作草案规范的一部分,但在一些非主流/移动/旧浏览器中可能还不支持它。您可以退回到querySelector(如果支持的话)。同样值得一提的是那份文件。activeElement将返回文档。即使浏览器窗口没有焦点,也没有焦点。
The following code will work around this issue and fall back to querySelector
giving a little better support.
下面的代码将处理这个问题,并返回到querySelector,提供更好的支持。
var focused = document.activeElement;
if (!focused || focused == document.body)
focused = null;
else if (document.querySelector)
focused = document.querySelector(":focus");
An addition thing to note is the performance difference between these two methods. Querying the document with selectors will always be much slower than accessing the activeElement
property. See this jsperf.com test.
需要注意的是这两个方法的性能差异。使用选择器查询文档总是比访问activeElement属性慢得多。看到这个jsperf.com测试。
#5
13
document.activeElement
may default to the <body>
element if no focusable elements are in focus. Additionally, if an element is focused and the browser window is blurred, activeElement
will continue to hold the focused element.
文档。如果没有焦点元素,activeElement可能默认为元素。此外,如果一个元素是焦点,浏览器窗口是模糊的,那么activeElement将继续保存焦点元素。
If either of these two behaviors are not desirable, consider a CSS-based approach: document.querySelector( ':focus' )
.
如果这两种行为都不可取,考虑使用基于css的方法:document。querySelector(“:焦点”)。
#6
12
By itself, document.activeElement
can still return an element if the document isn't focused (and thus nothing in the document is focused!)
文档本身。如果文档没有焦点,activeElement仍然可以返回一个元素(因此文档中没有焦点!)
You may want that behavior, or it may not matter (e.g. within a keydown
event), but if you need to know something is actually focused, you can additionally check document.hasFocus()
.
您可能想要这种行为,或者它可能不重要(例如,在一个keydown事件中),但是如果您需要知道某些事情实际上是集中的,您可以另外检查document.hasFocus()。
The following will give you the focused element if there is one, or else null
.
如果有一个焦点元素或else null,下面将给出焦点元素。
var focused_element = null;
if (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
) {
focused_element = document.activeElement;
}
To check whether a specific element has focus, it's simpler:
要检查某个特定元素是否有焦点,比较简单:
var input_focused = document.activeElement === input && document.hasFocus();
To check whether anything is focused, it's more complex again:
为了检查是否有任何东西是集中的,它再次变得更加复杂:
var anything_is_focused = (
document.hasFocus() &&
document.activeElement !== null &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
);
Robustness Note: In the code where it the checks against document.body
and document.documentElement
, this is because some browsers return one of these or null
when nothing is focused.
健壮性注意:在代码中,它检查文档。身体和文档。documentElement,这是因为一些浏览器在没有焦点的情况下返回其中一个或null。
It doesn't account for if the <body>
(or maybe <html>
) had a tabIndex
attribute and thus could actually be focused. If you're writing a library or something and want it to be robust, you should probably handle that somehow.
它并不说明(或者)是否具有tabIndex属性,因此实际上可以集中。如果您正在编写一个库或其他东西,并且希望它是健壮的,那么您应该以某种方式处理它。
Here's a (heavy airquotes) "one-liner" version of getting the focused element, which is conceptually more complicated because you have to know about short-circuiting, and y'know, it obviously doesn't fit on one line, assuming you want it to be readable.
I'm not gonna recommend this one. But if you're a 1337 hax0r, idk... it's there.
You could also remove the || null
part if you don't mind getting false
in some cases. (You could still get null
if document.activeElement
is null
):
这是一个(重airquotes)“单行”的获取焦点元素的版本,这在概念上更加复杂,因为你必须了解短路,你知道,它显然不适合一行,假设你希望它是可读的。我不推荐这个。但是如果你是1337 hax0r, idk…它的存在。如果您不介意在某些情况下得到false,您也可以删除|| null部分。(如果文档,仍然可以得到null。activeElement是null):
var focused_element = (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement &&
document.activeElement
) || null;
For checking if a specific element is focused, alternatively you could use events, but this way requires setup (and potentially teardown), and importantly, assumes an initial state:
为了检查特定的元素是否集中,或者您可以使用事件,但是这种方式需要设置(并且可能会被删除),重要的是,假设初始状态:
var input_focused = false;
input.addEventListener("focus", function() {
input_focused = true;
});
input.addEventListener("blur", function() {
input_focused = false;
});
You could fix the initial state assumption by using the non-evented way, but then you might as well just use that instead.
你可以用不显式的方法来修正初始状态假设,但你也可以用它来代替。
#7
10
I liked the approach used by Joel S, but I also love the simplicity of document.activeElement
. I used jQuery and combined the two. Older browsers that don't support document.activeElement
will use jQuery.data()
to store the value of 'hasFocus'. Newer browsers will use document.activeElement
. I assume that document.activeElement
will have better performance.
我喜欢Joel S使用的方法,但我也喜欢document.activeElement的简单性。我使用jQuery将两者结合起来。不支持文档的旧浏览器。activeElement将使用jQuery.data()来存储“hasFocus”的值。更新的浏览器将使用document.activeElement。我假设文档。activeElement将具有更好的性能。
(function($) {
var settings;
$.fn.focusTracker = function(options) {
settings = $.extend({}, $.focusTracker.defaults, options);
if (!document.activeElement) {
this.each(function() {
var $this = $(this).data('hasFocus', false);
$this.focus(function(event) {
$this.data('hasFocus', true);
});
$this.blur(function(event) {
$this.data('hasFocus', false);
});
});
}
return this;
};
$.fn.hasFocus = function() {
if (this.length === 0) { return false; }
if (document.activeElement) {
return this.get(0) === document.activeElement;
}
return this.data('hasFocus');
};
$.focusTracker = {
defaults: {
context: 'body'
},
focusedElement: function(context) {
var focused;
if (!context) { context = settings.context; }
if (document.activeElement) {
if ($(document.activeElement).closest(context).length > 0) {
focused = document.activeElement;
}
} else {
$(':visible:enabled', context).each(function() {
if ($(this).data('hasFocus')) {
focused = this;
return false;
}
});
}
return $(focused);
}
};
})(jQuery);
#8
9
A little helper that I've used for these purposes in Mootools:
我在Mootools中使用的一个小助手:
FocusTracker = {
startFocusTracking: function() {
this.store('hasFocus', false);
this.addEvent('focus', function() { this.store('hasFocus', true); });
this.addEvent('blur', function() { this.store('hasFocus', false); });
},
hasFocus: function() {
return this.retrieve('hasFocus');
}
}
Element.implement(FocusTracker);
This way you can check if element has focus with el.hasFocus()
provided that startFocusTracking()
has been called on the given element.
通过这种方式,您可以检查元素是否与el.hasFocus()有关,提供了在给定元素上调用startFocusTracking()的方法。
#9
7
JQuery does support the :focus
pseudo-class as of current. If you are looking for it in the JQuery documentation, check under "Selectors" where it points you to the W3C CSS docs. I've tested with Chrome, FF, and IE 7+. Note that for it to work in IE, <!DOCTYPE...
must exist on the html page. Here is an example assuming you've assigned an id to the element that has focus:
JQuery支持:focus伪类。如果您正在JQuery文档中寻找它,请在“选择器”下检查,它将您指向W3C CSS文档。我测试过Chrome, FF和IE 7+。注意,要让它在IE中工作,
$(":focus").each(function() {
alert($(this).attr("id") + " has focus!");
});
#10
6
There are potential problems with using document.activeElement. Consider:
使用document.activeElement可能存在一些问题。考虑:
<div contentEditable="true">
<div>Some text</div>
<div>Some text</div>
<div>Some text</div>
</div>
If the user focuses on an inner-div, then document.activeElement still references the outer div. You cannot use document.activeElement to determine which of the inner div's has focus.
如果用户关注内部div,那么文档。activeElement仍然引用外部div。不能使用document。activeElement用于确定哪些内部div具有焦点。
The following function gets around this, and returns the focused node:
下面的函数绕过这个,返回被关注的节点:
function active_node(){
return window.getSelection().anchorNode;
}
If you would rather get the focused element, use:
如果你想获得焦点元素,请使用:
function active_element(){
var anchor = window.getSelection().anchorNode;
if(anchor.nodeType == 3){
return anchor.parentNode;
}else if(anchor.nodeType == 1){
return anchor;
}
}
#11
6
If you want to get a object that is instance of Element
, you must use document.activeElement
, but if you want to get a object that is instance of Text
, you must to use document.getSelection().focusNode
.
如果您想获得一个元素实例的对象,您必须使用document。activeElement,但是如果您想获得一个文本实例的对象,您必须使用document.getSelection(). focusnode。
I hope helps.
我希望有帮助。
#12
5
Reading other answers, and trying myself, it seems document.activeElement
will give you the element you need in most browsers.
阅读其他答案,并尝试自己,它似乎是文件。activeElement将为您提供在大多数浏览器中需要的元素。
If you have a browser that doesn't support document.activeElement if you have jQuery around, you should be able populate it on all focus events with something very simple like this (untested as I don't have a browser meeting those criteria to hand):
如果你有一个不支持文档的浏览器。activeElement如果你身边有jQuery,你应该可以用一些非常简单的东西来填充所有焦点事件(没有经过测试,因为我手头没有符合这些标准的浏览器):
if (typeof document.activeElement === 'undefined') { // Check browser doesn't do it anyway
$('*').live('focus', function () { // Attach to all focus events using .live()
document.activeElement = this; // Set activeElement to the element that has been focussed
});
}
#13
5
If you're using jQuery, you can use this to find out if an element is active:
如果您正在使用jQuery,您可以使用它来查找某个元素是否处于活动状态:
$("input#id").is(":active");
#14
4
With dojo, you can use dijit.getFocus()
使用dojo,您可以使用dijit.getFocus()
#15
3
Just putting this here to give the solution I eventually came up with.
把这个放到这里来给出最终的解。
I created a property called document.activeInputArea, and used jQuery's HotKeys addon to trap keyboard events for arrow keys, tab and enter, and I created an event handler for clicking into input elements.
我创建了一个名为document的属性。activeInputArea,使用jQuery的HotKeys addon捕获键、tab和enter的键盘事件,我创建了一个事件处理程序,用于单击输入元素。
Then I adjusted the activeInputArea every time focus changed, so I could use that property to find out where I was.
然后每次焦点改变时,我都会调整activeInputArea,这样我就可以使用这个属性来找出我在哪里。
It's easy to screw this up though, because if you have a bug in the system and focus isn't where you think it is, then its very hard to restore the correct focus.
不过,搞砸这个很容易,因为如果系统中有一个错误,焦点不在您认为的位置,那么就很难恢复正确的焦点。
#16
3
An almost browser independent way to achieve this was made by Quirksmode a long time ago. It could have issues with Safari as Safari does not always set events on the same elements than Chrome or Firefox does. Sometimes Safari even sets the event on the textnode instead of the containing element. This can be rectified afterwards ofcourse (by checking the nodeType).
一种几乎完全独立于浏览器的方式来实现这一点,是由Quirksmode在很久以前提出的。它可能会遇到Safari的问题,因为Safari并不总是像Chrome或Firefox那样在相同的元素上设置事件。有时Safari甚至会在textnode上设置事件,而不是包含元素。这可以在事后纠正(通过检查nodeType)。
Here it is:
这里是:
function getFocus(e){
var focused;
if (!e) var e = window.event;
if (e.target) focused = e.target;
else if (e.srcElement) focused = e.srcElement;
if (focused.nodeType == 3) focused = focused.parentNode;
if (document.querySelector) {
return focused.id;
} else if (!focused || focused == document.documentElement) {
return focused;
}
}
Hope it helps.
希望它可以帮助。
Thanks to Quirksmode
由于Quirksmode
#17
2
I have found the following snippet to be useful when trying to determine which element currently has focus. Copy the following into the console of your browser, and every second it will print out the details of the current element that has focus.
我发现以下代码片段在尝试确定哪个元素当前具有焦点时非常有用。将以下内容复制到浏览器的控制台中,每过一秒钟,它就会打印出具有焦点的当前元素的详细信息。
setInterval(function() { console.log(document.querySelector(":focus")); }, 1000);
Feel free to modify the console.log
to log out something different to help you pinpoint the exact element if printing out the whole element does not help you pinpoint the element.
请随意修改控制台。如果打印出整个元素并不能帮助您确定元素,那么日志记录一些不同的内容来帮助您精确地确定元素。
#1
1192
Use document.activeElement
, it is supported in all major browsers.
使用文档。activeElement在所有主流浏览器中都支持。
Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.
在此之前,如果您试图找出什么表单字段具有焦点,您就不能。要在旧的浏览器中模拟检测,请向所有字段添加“焦点”事件处理程序,并在一个变量中记录最后聚焦的字段。添加一个“blur”处理程序,清除最后焦点字段的blur事件中的变量。
Related links:
相关链接:
- activeElement Browser Compatibility
- activeElement浏览器兼容性
- jQuery alternative for document.activeElement
- jQuery选择document.activeElement
#2
106
As said by JW, you can't find the current focused element, at least in a browser-independent way. But if your app is IE only (some are...), you can find it the following way :
正如JW所说,您无法找到当前的焦点元素,至少是在浏览器独立的方式中。但如果你的应用程序是IE(有些是…),你可以通过以下方式找到:
document.activeElement
EDIT: It looks like IE did not have everything wrong after all, this is part of HTML5 draft and seems to be supported by the latest version of Chrome, Safari and Firefox at least.
编辑:看起来IE并没有什么问题,这是HTML5草案的一部分,并且至少支持最新版本的Chrome、Safari和Firefox。
#3
76
If you can use jQuery, it now supports :focus, just make sure you are using version 1.6+.
如果您可以使用jQuery,它现在支持:focus,请确保您使用的是1.6+版本。
This statement will get you the currently focused element.
此语句将为您提供当前关注的元素。
$(":focus")
From: How to select an element that has focus on it with jQuery
From: How to select a element that has focus on it with jQuery
#4
38
document.activeElement
is now part of the HTML5 working draft specification, but it might not yet be supported in some non-major/mobile/older browsers. You can fall back to querySelector
(if that is supported). It's also worth mentioning that document.activeElement
will return document.body
if no element is focused — even if the browser window doesn't have focus.
文档。activeElement现在是HTML5工作草案规范的一部分,但在一些非主流/移动/旧浏览器中可能还不支持它。您可以退回到querySelector(如果支持的话)。同样值得一提的是那份文件。activeElement将返回文档。即使浏览器窗口没有焦点,也没有焦点。
The following code will work around this issue and fall back to querySelector
giving a little better support.
下面的代码将处理这个问题,并返回到querySelector,提供更好的支持。
var focused = document.activeElement;
if (!focused || focused == document.body)
focused = null;
else if (document.querySelector)
focused = document.querySelector(":focus");
An addition thing to note is the performance difference between these two methods. Querying the document with selectors will always be much slower than accessing the activeElement
property. See this jsperf.com test.
需要注意的是这两个方法的性能差异。使用选择器查询文档总是比访问activeElement属性慢得多。看到这个jsperf.com测试。
#5
13
document.activeElement
may default to the <body>
element if no focusable elements are in focus. Additionally, if an element is focused and the browser window is blurred, activeElement
will continue to hold the focused element.
文档。如果没有焦点元素,activeElement可能默认为元素。此外,如果一个元素是焦点,浏览器窗口是模糊的,那么activeElement将继续保存焦点元素。
If either of these two behaviors are not desirable, consider a CSS-based approach: document.querySelector( ':focus' )
.
如果这两种行为都不可取,考虑使用基于css的方法:document。querySelector(“:焦点”)。
#6
12
By itself, document.activeElement
can still return an element if the document isn't focused (and thus nothing in the document is focused!)
文档本身。如果文档没有焦点,activeElement仍然可以返回一个元素(因此文档中没有焦点!)
You may want that behavior, or it may not matter (e.g. within a keydown
event), but if you need to know something is actually focused, you can additionally check document.hasFocus()
.
您可能想要这种行为,或者它可能不重要(例如,在一个keydown事件中),但是如果您需要知道某些事情实际上是集中的,您可以另外检查document.hasFocus()。
The following will give you the focused element if there is one, or else null
.
如果有一个焦点元素或else null,下面将给出焦点元素。
var focused_element = null;
if (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
) {
focused_element = document.activeElement;
}
To check whether a specific element has focus, it's simpler:
要检查某个特定元素是否有焦点,比较简单:
var input_focused = document.activeElement === input && document.hasFocus();
To check whether anything is focused, it's more complex again:
为了检查是否有任何东西是集中的,它再次变得更加复杂:
var anything_is_focused = (
document.hasFocus() &&
document.activeElement !== null &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
);
Robustness Note: In the code where it the checks against document.body
and document.documentElement
, this is because some browsers return one of these or null
when nothing is focused.
健壮性注意:在代码中,它检查文档。身体和文档。documentElement,这是因为一些浏览器在没有焦点的情况下返回其中一个或null。
It doesn't account for if the <body>
(or maybe <html>
) had a tabIndex
attribute and thus could actually be focused. If you're writing a library or something and want it to be robust, you should probably handle that somehow.
它并不说明(或者)是否具有tabIndex属性,因此实际上可以集中。如果您正在编写一个库或其他东西,并且希望它是健壮的,那么您应该以某种方式处理它。
Here's a (heavy airquotes) "one-liner" version of getting the focused element, which is conceptually more complicated because you have to know about short-circuiting, and y'know, it obviously doesn't fit on one line, assuming you want it to be readable.
I'm not gonna recommend this one. But if you're a 1337 hax0r, idk... it's there.
You could also remove the || null
part if you don't mind getting false
in some cases. (You could still get null
if document.activeElement
is null
):
这是一个(重airquotes)“单行”的获取焦点元素的版本,这在概念上更加复杂,因为你必须了解短路,你知道,它显然不适合一行,假设你希望它是可读的。我不推荐这个。但是如果你是1337 hax0r, idk…它的存在。如果您不介意在某些情况下得到false,您也可以删除|| null部分。(如果文档,仍然可以得到null。activeElement是null):
var focused_element = (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement &&
document.activeElement
) || null;
For checking if a specific element is focused, alternatively you could use events, but this way requires setup (and potentially teardown), and importantly, assumes an initial state:
为了检查特定的元素是否集中,或者您可以使用事件,但是这种方式需要设置(并且可能会被删除),重要的是,假设初始状态:
var input_focused = false;
input.addEventListener("focus", function() {
input_focused = true;
});
input.addEventListener("blur", function() {
input_focused = false;
});
You could fix the initial state assumption by using the non-evented way, but then you might as well just use that instead.
你可以用不显式的方法来修正初始状态假设,但你也可以用它来代替。
#7
10
I liked the approach used by Joel S, but I also love the simplicity of document.activeElement
. I used jQuery and combined the two. Older browsers that don't support document.activeElement
will use jQuery.data()
to store the value of 'hasFocus'. Newer browsers will use document.activeElement
. I assume that document.activeElement
will have better performance.
我喜欢Joel S使用的方法,但我也喜欢document.activeElement的简单性。我使用jQuery将两者结合起来。不支持文档的旧浏览器。activeElement将使用jQuery.data()来存储“hasFocus”的值。更新的浏览器将使用document.activeElement。我假设文档。activeElement将具有更好的性能。
(function($) {
var settings;
$.fn.focusTracker = function(options) {
settings = $.extend({}, $.focusTracker.defaults, options);
if (!document.activeElement) {
this.each(function() {
var $this = $(this).data('hasFocus', false);
$this.focus(function(event) {
$this.data('hasFocus', true);
});
$this.blur(function(event) {
$this.data('hasFocus', false);
});
});
}
return this;
};
$.fn.hasFocus = function() {
if (this.length === 0) { return false; }
if (document.activeElement) {
return this.get(0) === document.activeElement;
}
return this.data('hasFocus');
};
$.focusTracker = {
defaults: {
context: 'body'
},
focusedElement: function(context) {
var focused;
if (!context) { context = settings.context; }
if (document.activeElement) {
if ($(document.activeElement).closest(context).length > 0) {
focused = document.activeElement;
}
} else {
$(':visible:enabled', context).each(function() {
if ($(this).data('hasFocus')) {
focused = this;
return false;
}
});
}
return $(focused);
}
};
})(jQuery);
#8
9
A little helper that I've used for these purposes in Mootools:
我在Mootools中使用的一个小助手:
FocusTracker = {
startFocusTracking: function() {
this.store('hasFocus', false);
this.addEvent('focus', function() { this.store('hasFocus', true); });
this.addEvent('blur', function() { this.store('hasFocus', false); });
},
hasFocus: function() {
return this.retrieve('hasFocus');
}
}
Element.implement(FocusTracker);
This way you can check if element has focus with el.hasFocus()
provided that startFocusTracking()
has been called on the given element.
通过这种方式,您可以检查元素是否与el.hasFocus()有关,提供了在给定元素上调用startFocusTracking()的方法。
#9
7
JQuery does support the :focus
pseudo-class as of current. If you are looking for it in the JQuery documentation, check under "Selectors" where it points you to the W3C CSS docs. I've tested with Chrome, FF, and IE 7+. Note that for it to work in IE, <!DOCTYPE...
must exist on the html page. Here is an example assuming you've assigned an id to the element that has focus:
JQuery支持:focus伪类。如果您正在JQuery文档中寻找它,请在“选择器”下检查,它将您指向W3C CSS文档。我测试过Chrome, FF和IE 7+。注意,要让它在IE中工作,
$(":focus").each(function() {
alert($(this).attr("id") + " has focus!");
});
#10
6
There are potential problems with using document.activeElement. Consider:
使用document.activeElement可能存在一些问题。考虑:
<div contentEditable="true">
<div>Some text</div>
<div>Some text</div>
<div>Some text</div>
</div>
If the user focuses on an inner-div, then document.activeElement still references the outer div. You cannot use document.activeElement to determine which of the inner div's has focus.
如果用户关注内部div,那么文档。activeElement仍然引用外部div。不能使用document。activeElement用于确定哪些内部div具有焦点。
The following function gets around this, and returns the focused node:
下面的函数绕过这个,返回被关注的节点:
function active_node(){
return window.getSelection().anchorNode;
}
If you would rather get the focused element, use:
如果你想获得焦点元素,请使用:
function active_element(){
var anchor = window.getSelection().anchorNode;
if(anchor.nodeType == 3){
return anchor.parentNode;
}else if(anchor.nodeType == 1){
return anchor;
}
}
#11
6
If you want to get a object that is instance of Element
, you must use document.activeElement
, but if you want to get a object that is instance of Text
, you must to use document.getSelection().focusNode
.
如果您想获得一个元素实例的对象,您必须使用document。activeElement,但是如果您想获得一个文本实例的对象,您必须使用document.getSelection(). focusnode。
I hope helps.
我希望有帮助。
#12
5
Reading other answers, and trying myself, it seems document.activeElement
will give you the element you need in most browsers.
阅读其他答案,并尝试自己,它似乎是文件。activeElement将为您提供在大多数浏览器中需要的元素。
If you have a browser that doesn't support document.activeElement if you have jQuery around, you should be able populate it on all focus events with something very simple like this (untested as I don't have a browser meeting those criteria to hand):
如果你有一个不支持文档的浏览器。activeElement如果你身边有jQuery,你应该可以用一些非常简单的东西来填充所有焦点事件(没有经过测试,因为我手头没有符合这些标准的浏览器):
if (typeof document.activeElement === 'undefined') { // Check browser doesn't do it anyway
$('*').live('focus', function () { // Attach to all focus events using .live()
document.activeElement = this; // Set activeElement to the element that has been focussed
});
}
#13
5
If you're using jQuery, you can use this to find out if an element is active:
如果您正在使用jQuery,您可以使用它来查找某个元素是否处于活动状态:
$("input#id").is(":active");
#14
4
With dojo, you can use dijit.getFocus()
使用dojo,您可以使用dijit.getFocus()
#15
3
Just putting this here to give the solution I eventually came up with.
把这个放到这里来给出最终的解。
I created a property called document.activeInputArea, and used jQuery's HotKeys addon to trap keyboard events for arrow keys, tab and enter, and I created an event handler for clicking into input elements.
我创建了一个名为document的属性。activeInputArea,使用jQuery的HotKeys addon捕获键、tab和enter的键盘事件,我创建了一个事件处理程序,用于单击输入元素。
Then I adjusted the activeInputArea every time focus changed, so I could use that property to find out where I was.
然后每次焦点改变时,我都会调整activeInputArea,这样我就可以使用这个属性来找出我在哪里。
It's easy to screw this up though, because if you have a bug in the system and focus isn't where you think it is, then its very hard to restore the correct focus.
不过,搞砸这个很容易,因为如果系统中有一个错误,焦点不在您认为的位置,那么就很难恢复正确的焦点。
#16
3
An almost browser independent way to achieve this was made by Quirksmode a long time ago. It could have issues with Safari as Safari does not always set events on the same elements than Chrome or Firefox does. Sometimes Safari even sets the event on the textnode instead of the containing element. This can be rectified afterwards ofcourse (by checking the nodeType).
一种几乎完全独立于浏览器的方式来实现这一点,是由Quirksmode在很久以前提出的。它可能会遇到Safari的问题,因为Safari并不总是像Chrome或Firefox那样在相同的元素上设置事件。有时Safari甚至会在textnode上设置事件,而不是包含元素。这可以在事后纠正(通过检查nodeType)。
Here it is:
这里是:
function getFocus(e){
var focused;
if (!e) var e = window.event;
if (e.target) focused = e.target;
else if (e.srcElement) focused = e.srcElement;
if (focused.nodeType == 3) focused = focused.parentNode;
if (document.querySelector) {
return focused.id;
} else if (!focused || focused == document.documentElement) {
return focused;
}
}
Hope it helps.
希望它可以帮助。
Thanks to Quirksmode
由于Quirksmode
#17
2
I have found the following snippet to be useful when trying to determine which element currently has focus. Copy the following into the console of your browser, and every second it will print out the details of the current element that has focus.
我发现以下代码片段在尝试确定哪个元素当前具有焦点时非常有用。将以下内容复制到浏览器的控制台中,每过一秒钟,它就会打印出具有焦点的当前元素的详细信息。
setInterval(function() { console.log(document.querySelector(":focus")); }, 1000);
Feel free to modify the console.log
to log out something different to help you pinpoint the exact element if printing out the whole element does not help you pinpoint the element.
请随意修改控制台。如果打印出整个元素并不能帮助您确定元素,那么日志记录一些不同的内容来帮助您精确地确定元素。