最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select currently focused element - Stack Overflow

programmeradmin2浏览0评论

I'd like to find the currently focused element in the whole document. I tried using the :focus pseudoclass introduced with jQuery 1.6:

$(document).find(":focus")

But $(document).find(":focus").length always returns 0

I'd like to find the currently focused element in the whole document. I tried using the :focus pseudoclass introduced with jQuery 1.6:

$(document).find(":focus")

But $(document).find(":focus").length always returns 0

Share Improve this question edited Feb 5, 2012 at 11:26 James Allardice 166k22 gold badges334 silver badges315 bronze badges asked Feb 5, 2012 at 11:05 ValentinoValentino 5427 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 14

You should be able to use the activeElement property of the document:

var focus = $(document.activeElement);

If you look at the jQuery documentation for :focus it makes this perfectly clear:

If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

It's worth noting that if no element currently has focus, activeElement will refer to the body.

As with other pseudo-class selectors (those that begin with a ":"), it is remended 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 want an alternative to $( document.activeElement ) which will retrieve the current element that has focus you can use :

$(document).delegate( "*", "focus blur", function( event ) {
    var elem = $( this );
    //  here use elem.is( ":focus" ) which is your element that has focus
   //for example  : 
    elem.toggleClass( "focused", elem.is( ":focus" ) );
});
发布评论

评论列表(0)

  1. 暂无评论