如何找出哪个 DOM 元素具有焦点? [英] How do I find out which DOM element has the focus?
问题描述
我想在 JavaScript 中找出当前具有焦点的元素.我一直在浏览 DOM,但还没有找到我需要的东西.有没有办法做到这一点,以及如何做到这一点?
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, and how?
我找这个的原因:
我正在尝试使箭头和 enter
之类的键在输入元素表中导航.Tab 现在可以工作,但输入和箭头似乎默认情况下不起作用.我已经设置了关键处理部分,但现在我需要弄清楚如何在事件处理函数中移动焦点.
I'm trying to make keys like the arrows and enter
navigate through a table of input elements. Tab works now, but enter, and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.
推荐答案
使用 document.activeElement
,所有主流浏览器都支持.
Use document.activeElement
, it is supported in all major browsers.
以前,如果您试图找出哪个表单字段具有焦点,则无法找到.要在旧浏览器中模拟检测,请向所有字段添加焦点"事件处理程序,并将最后一个焦点字段记录在变量中.添加模糊"处理程序以在最后聚焦的字段的模糊事件时清除变量.
Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.
如果需要删除activeElement
,可以使用blur;document.activeElement.blur()
.它会将 activeElement
更改为 body
.
If you need to remove the activeElement
you can use blur; document.activeElement.blur()
. It will change the activeElement
to body
.
相关链接:
这篇关于如何找出哪个 DOM 元素具有焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!