<分区>
Possible Duplicates:
How to determine which html page element has focus?
How do I find out which Javascript element has focus?
有没有办法确定当前文档中的哪个元素具有焦点?理想情况下无需遍历每个元素。
<分区>
Possible Duplicates:
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
属性,它可以实现你想要的。
对于旧版浏览器,你需要这个 hack 来模拟属性:
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);
}
关于javascript - 确定哪个元素具有焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1009777/