Aro*_*eel 83
使用该document.activeElement
属性.
document.activeElement
Chrome 2 +,Firefox 3 +,IE4 +,Opera 9.6+和Safari 4+支持该属性.
请注意,此属性仅包含接受击键的元素(例如表单元素).
Pao*_*ino 47
看看这篇博文.它提供了一种解决方法,因此document.activeElement
适用于所有浏览器.
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);
}
Run Code Online (Sandbox Code Playgroud)
需要注意的事项:
这种实施略微过于悲观; 如果浏览器窗口失去焦点,则activeElement设置为null(因为输入控件也会失去焦点).如果您的应用程序需要activeElement值,即使浏览器窗口没有焦点,您也可以删除blur事件侦听器.
只是为了记录,有点晚了,当然在旧浏览器中不支持:
var element = document.querySelector(":focus");
Run Code Online (Sandbox Code Playgroud)
应该适用于所有元素(例如锚点).
归档时间: |
|
查看次数: |
57059 次 |
最近记录: |