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

后端 未结 16 1686
悲&欢浪女
悲&欢浪女 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:47

    Just putting this here to give the solution I eventually came up with.

    I created a property called document.activeInputArea, and used jQuery's HotKeys addon to trap keyboard events for arrow keys, tab and enter, and I created an event handler for clicking into input elements.

    Then I adjusted the activeInputArea every time focus changed, so I could use that property to find out where I was.

    It's easy to screw this up though, because if you have a bug in the system and focus isn't where you think it is, then its very hard to restore the correct focus.

提交回复
热议问题