Using jQuery to test if an input has focus

后端 未结 15 1144
梦谈多话
梦谈多话 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:27

    There is no :focus, but there is :selected http://docs.jquery.com/Selectors/selected

    but if you want to change how things look based on what is selected you should probably be working with the blur events.

    http://docs.jquery.com/Events/blur

    0 讨论(0)
  • 2020-11-22 06:28

    Here’s a more robust answer than the currently accepted one:

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

    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.

    (Taken from this gist by Ben Alman.)

    0 讨论(0)
  • 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 );
    
    0 讨论(0)
提交回复
热议问题