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

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

    JQuery does support the :focus pseudo-class as of current. If you are looking for it in the JQuery documentation, check under "Selectors" where it points you to the W3C CSS docs. I've tested with Chrome, FF, and IE 7+. Note that for it to work in IE, must exist on the html page. Here is an example assuming you've assigned an id to the element that has focus:

    $(":focus").each(function() {
      alert($(this).attr("id") + " has focus!");
    });
    

提交回复
热议问题