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

后端 未结 10 1110
北恋
北恋 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 01:01
        $('*:focus')
    

    (Necro ftw, but still valid and useful)

    0 讨论(0)
  • 2020-11-30 01:02

    Here is a succinct way to do it.

    $(document.activeElement)
    

    or to plug it into your example..

    if ($('form#contact input]')[0]!=$(document.activeElement)) { ... }
    
    0 讨论(0)
  • 2020-11-30 01:12

    jQuery 1.6 now has a dedicated :focus selector.

    0 讨论(0)
  • 2020-11-30 01:13

    No, there isn't.

    However, you can simulate it like this:

    $(':input')
        .data('focused', false)
        .focus(function() { $.data(this, 'focused', true); })
        .blur(function() { $.data(this, 'focused', false); });
    
    0 讨论(0)
提交回复
热议问题