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

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

    There are potential problems with using document.activeElement. Consider:

    Some text
    Some text
    Some text

    If the user focuses on an inner-div, then document.activeElement still references the outer div. You cannot use document.activeElement to determine which of the inner div's has focus.

    The following function gets around this, and returns the focused node:

    function active_node(){
      return window.getSelection().anchorNode;
    }
    

    If you would rather get the focused element, use:

    function active_element(){
      var anchor = window.getSelection().anchorNode;
      if(anchor.nodeType == 3){
            return anchor.parentNode;
      }else if(anchor.nodeType == 1){
            return anchor;
      }
    }
    

提交回复
热议问题