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

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

    Reading other answers, and trying myself, it seems document.activeElement will give you the element you need in most browsers.

    If you have a browser that doesn't support document.activeElement if you have jQuery around, you should be able populate it on all focus events with something very simple like this (untested as I don't have a browser meeting those criteria to hand):

    if (typeof document.activeElement === 'undefined') { // Check browser doesn't do it anyway
      $('*').live('focus', function () { // Attach to all focus events using .live()
        document.activeElement = this; // Set activeElement to the element that has been focussed
      });
    }
    

提交回复
热议问题