Select currently focused element

泪湿孤枕 提交于 2019-12-10 09:24:15

问题


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


回答1:


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.




回答2:


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 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" ) );
});


来源:https://stackoverflow.com/questions/9148707/select-currently-focused-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!