I want to find which element is on focus. Also, when a user opens multiple windows/tab, i'd li开发者_如何学编程ke to know which window/tab is on the focus.
In plain JavaScript (i.e. without any frameworks like jQuery, MooTools, etc.):
var focusedElement;
document.addEventListener("focus", function(e) {
focusedElement = e.target;
}, true);
document.addEventListener("blur", function(e) {
focusedElement = null;
}, true);
Basically, whenever an element gains focus, we save that element to a variable, and when the element loses focus, we reset the variable.
In HTML 5, there's a specific attribute for accessing the currently focused element:
var focusedElement = document.activeElement;
Using jQuery, you can use this to find focus:
$("body").bind("onfocus", function (e) {
alert("focus: " + e.target); // e.target is the element with focus
});
You need only one handler using event delegation - the event percolates up the DOM tree until it is handled, so you can make do with one handler for the whole document.
See jQuery documentation for their event object and event functions, it makes it much simpler to do this in a cross-browser fashion.
Multiple browser windows or tabs is not accessible from Javascript.
Here's a tip. Anyway, you have to add event handler for each input element on a page. Only alternative is IE-only: document.activeElement
精彩评论