Is there a 'has focus' in JavaScript (or jQuery)?

后端 未结 10 1240
北恋
北恋 2020-11-30 00:36

Is there something I can do like this (perhap via a plugin)

if ( ! $(\'form#contact input]\').hasFocus()) {
  $(\'form#contact input:first]\').focus();
}
         


        
10条回答
  •  北海茫月
    2020-11-30 00:52

    There is no native solution but yes there is a more elegant way you can do it:

    jQuery.extend(jQuery.expr[':'], {
      focus: "a == document.activeElement"
    });
    

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

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

    or:

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

提交回复
热议问题