Using jQuery to test if an input has focus

后端 未结 15 1142
梦谈多话
梦谈多话 2020-11-22 05:42

On the front page of a site I am building, several

s use the CSS :hover pseudo-class to add a border when the mouse is over them. One of
15条回答
  •  孤街浪徒
    2020-11-22 06:29

    jQuery 1.6+

    jQuery added a :focus selector so we no longer need to add it ourselves. Just use $("..").is(":focus")

    jQuery 1.5 and below

    Edit: As times change, we find better methods for testing focus, the new favorite is this gist from Ben Alman:

    jQuery.expr[':'].focus = function( elem ) {
      return elem === document.activeElement && ( elem.type || elem.href );
    };
    

    Quoted from Mathias Bynens here:

    Note that the (elem.type || elem.href) test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.

    You're defining a new selector. See Plugins/Authoring. Then you can do:

    if ($("...").is(":focus")) {
      ...
    }
    

    or:

    $("input:focus").doStuff();
    

    Any jQuery

    If you just want to figure out which element has focus, you can use

    $(document.activeElement)
    

    If you aren't sure if the version will be 1.6 or lower, you can add the :focus selector if it is missing:

    (function ( $ ) {
        var filters = $.expr[":"];
        if ( !filters.focus ) { 
            filters.focus = function( elem ) {
               return elem === document.activeElement && ( elem.type || elem.href );
            };
        }
    })( jQuery );
    

提交回复
热议问题