jQuery alternative for document.activeElement

后端 未结 5 1402
青春惊慌失措
青春惊慌失措 2020-12-30 01:50

What I wanted to do is figure out whenever the user is engaged with an INPUT or TEXTAREA element and set a variable flag to true... and set that flag to false immediately af

相关标签:
5条回答
  • 2020-12-30 02:01

    You want the focus and blur event handlers. For example...

    var inFocus = false;
    $('input, textarea').focus(function() {
      inFocus = true;
    });
    
    $('input, textarea').blur(function() {
      inFocus = false;
    });
    

    I'm pretty sure that a comma will get you input OR textarea, but you get the idea if that doesn't pan out

    0 讨论(0)
  • 2020-12-30 02:12

    Iis the .blur() event what you're looking for?

    0 讨论(0)
  • 2020-12-30 02:15

    You can do something like this :

    var focusItem = null; 
    $('input, textarea').focus( function() { 
        focusItem = this; 
    });
    
    0 讨论(0)
  • 2020-12-30 02:17
    function getActive(){
       return $(document.activeElement).is('input') || $(document.activeElement).is('textarea');
    }
    
    0 讨论(0)
  • 2020-12-30 02:23

    For the original question about figuring out if the currently focused element is any of those user input elements, below should work:

    function isInputElementInFocus() {
        return $(document.activeElement).is(":input");
    }
    

    Conceptually I don't like this approach for generic case where you are listening to global events (like key strocks) and trying to decide if these should be handled by your global handler or be ignored because it is meant for someone else. The reason I don't like it because it's not future safe and also who knows what else that someone can be besides input elements.

    Another more robust but tricky to implement idea is to test if event is meant for an element that has tabIndex >= 0. The input elements have tabIndex === 0 set by default so it becomes more or less similar to above approach. You can easily check this by event.target.tabIndex >= 0 without need to rely on document.activeElement.

    The gotchas here (if you want to be generic) is that you also need to make sure that event.target element is neither in another branch in DOM hierarchy nor there is someone else between event.currentTarget and event.target that has tabIndex >= 0. You get the idea: This can become murky but I just thought to jot it down if someone else is in need of generic solution.

    0 讨论(0)
提交回复
热议问题