如何找出哪个DOM元素有焦点? [英] How do I find out which DOM element has the focus?

查看:85
本文介绍了如何找出哪个DOM元素有焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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?

我正在寻找的原因是:

我尝试使箭头和键进入导航一个输入元素表。标签现在工作,但输入,箭头不是默认情况下似乎。我已经设置了关键处理部分,但现在我需要弄清楚如何在事件处理函数中调整焦点。

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.

以前,如果你是试图找出什么样的字段有焦点,你不能。要在旧版浏览器中模拟检测,请在所有字段中添加一个focus事件处理程序,并将最后一个关注的字段记录在变量中。添加一个模糊处理程序来清除最后一个焦点字段的模糊事件的变量。

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 Browser Compatibility
  • jQuery alternative for document.activeElement

这篇关于如何找出哪个DOM元素有焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆