确定哪个元素具有焦点 [英] Determining which element has focus
本文介绍了确定哪个元素具有焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法确定文档中哪个元素目前有焦点?理想情况下,无需遍历任何元素。
Is there a way to determine which element within the document currently has focus? Ideally without having to walk through ever element.
推荐答案
重复:
- How to determine which html page element has focus?
- How do I find out which Javascript element has focus?
长话短说:
某些浏览器(最初只有IE,但Firefox 3和Safari跳上了马车)支持 document.activeElement
属性,它实现了你想要的。
Some browsers (originally only IE, but Firefox 3 and Safari jumped on the wagon) support the document.activeElement
property, which achieves what you want.
对于旧浏览器,你需要这个hack来模仿属性:
For older browsers, you need this hack to emulate the property:
function _dom_trackActiveElement(evt) {
if (evt && evt.target) {
document.activeElement = evt.target == document ? null : evt.target;
}
}
function _dom_trackActiveElementLost(evt) {
document.activeElement = null;
}
if (!document.activeElement) {
document.addEventListener("focus",_dom_trackActiveElement,true);
document.addEventListener("blur",_dom_trackActiveElementLost,true);
}
这篇关于确定哪个元素具有焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文