How do I find out which DOM element has the focus?

后端 未结 16 1495
悲&欢浪女
悲&欢浪女 2020-11-22 03:12

I would like to find out, in JavaScript, which element currently has focus. I\'ve been looking through the DOM and haven\'t found what I need, yet. Is there a way to do this

16条回答
  •  野性不改
    2020-11-22 03:52

    A little helper that I've used for these purposes in Mootools:

    FocusTracker = {
        startFocusTracking: function() {
           this.store('hasFocus', false);
           this.addEvent('focus', function() { this.store('hasFocus', true); });
           this.addEvent('blur', function() { this.store('hasFocus', false); });
        },
    
        hasFocus: function() {
           return this.retrieve('hasFocus');
        }
    }
    
    Element.implement(FocusTracker);
    

    This way you can check if element has focus with el.hasFocus() provided that startFocusTracking() has been called on the given element.

提交回复
热议问题