获取页面上当前激活(获得焦点)的元素
在 JavaScript 中,你可以使用 document.activeElement
属性来获取当前获得焦点的 DOM 元素。以下是几种不同场景下的实现方法:
1. 基本使用方法
// 获取当前获得焦点的元素
const activeElement = document.activeElement;// 检查元素是否存在并输出信息
if (activeElement) {console.log('当前激活的元素:', activeElement);console.log('元素标签名:', activeElement.tagName);console.log('元素ID:', activeElement.id);console.log('元素类名:', activeElement.className);
} else {console.log('当前没有元素获得焦点');
}
2. 实时监听焦点变化
// 监听文档焦点变化
document.addEventListener('focusin', (event) => {console.log('元素获得焦点:', event.target);
});document.addEventListener('focusout', (event) => {console.log('元素失去焦点:', event.target);
});// 也可以使用更通用的方法
function logActiveElement() {console.log('当前激活元素:', document.activeElement);
}// 定期检查(不推荐,仅作演示)
setInterval(logActiveElement, 1000);
3. React 中的实现
import { useState, useEffect } from 'react';function ActiveElementTracker() {const [activeElement, setActiveElement] = useState(null);useEffect(() => {function handleFocusChange() {setActiveElement(document.activeElement);}// 初始设置handleFocusChange();// 添加事件监听document.addEventListener('focusin', handleFocusChange);document.addEventListener('focusout', handleFocusChange);return () => {// 清除事件监听document.removeEventListener('focusin', handleFocusChange);document.removeEventListener('focusout', handleFocusChange);};}, []);return (<div><h3>当前激活的元素:</h3>{activeElement ? (<div><p>标签名: {activeElement.tagName}</p><p>ID: {activeElement.id || '无'}</p><p>类名: {activeElement.className || '无'}</p></div>) : (<p>没有元素获得焦点</p>)}<input type="text" placeholder="测试输入框1" /><input type="text" placeholder="测试输入框2" /><button>测试按钮</button></div>);
}
4. 检查特定元素是否激活
// 检查特定元素是否获得焦点
function isElementActive(selector) {const element = document.querySelector(selector);return element && element === document.activeElement;
}// 使用示例
if (isElementActive('#myInput')) {console.log('#myInput 当前获得焦点');
}
5. 处理 Shadow DOM 中的元素
function getDeepActiveElement() {let element = document.activeElement;while (element?.shadowRoot?.activeElement) {element = element.shadowRoot.activeElement;}return element;
}// 使用示例
const deepestActiveElement = getDeepActiveElement();
console.log('最深层激活元素:', deepestActiveElement);
注意事项
-
iframe 中的元素:如果要获取 iframe 中的激活元素,需要先访问 iframe 的 document 对象
const iframeActiveElement = document.getElementById('myIframe').contentDocument.activeElement;
-
浏览器兼容性:
document.activeElement
在所有现代浏览器中都支持良好 -
初始状态:页面加载时,
document.activeElement
通常是<body>
元素 -
可聚焦元素:不是所有元素都能获得焦点,只有特定的可聚焦元素(如 input, button, a 等)或设置了
tabindex
属性的元素才能获得焦点 -
性能考虑:频繁检查
document.activeElement
可能会影响性能,建议使用事件监听而非轮询