当前位置: 首页 > java >正文

获取页面上当前激活(获得焦点)的元素

在 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);

注意事项

  1. iframe 中的元素:如果要获取 iframe 中的激活元素,需要先访问 iframe 的 document 对象

    const iframeActiveElement = document.getElementById('myIframe').contentDocument.activeElement;
    
  2. 浏览器兼容性document.activeElement 在所有现代浏览器中都支持良好

  3. 初始状态:页面加载时,document.activeElement 通常是 <body> 元素

  4. 可聚焦元素:不是所有元素都能获得焦点,只有特定的可聚焦元素(如 input, button, a 等)或设置了 tabindex 属性的元素才能获得焦点

  5. 性能考虑:频繁检查 document.activeElement 可能会影响性能,建议使用事件监听而非轮询

http://www.xdnf.cn/news/9208.html

相关文章:

  • Frequent values/gcd区间
  • 行为型:中介者模式
  • C++11 中引入的`final` 关键字作用。
  • ImageMagick 是默认使用 CPU 来处理图像,也具备利用 GPU 加速的潜力
  • 数据库的事务(Transaction)
  • 路桥隧养护决策系统
  • atomic.Value 中存储的数据是否会被 GC
  • vue展示修改前后对比,并显示修改标注diff
  • 四足机器人环境监测系统相关问题
  • Mac 每日磁盘写入量异常高
  • AI如何颠覆财务预测?——用Python打造自动化智能分析系统
  • 基于Java,SpringBoot,Vue,UniAPP宠物洗护医疗喂养预约服务商城小程序管理系统设计
  • SQL Server 简介和与其它数据库对比
  • 联想小新笔记本电脑静电问题导致无法开机/充电的解决方案
  • 远程控制技术全面解析:找到适合你的最佳方案
  • 北京大学肖臻老师《区块链技术与应用》公开课:03-BTC-数据结构
  • 计算机网络的性能指标
  • 网络协议:[0-RTT 认证 ]
  • 在 LangGraph 中集成 Mem0 记忆系统教程
  • 【HarmonyOS5】Stage模型应用程序包结构详解
  • PDF处理控件Aspose.PDF教程:压缩 PDF 文档的完整指南
  • OpenCV CUDA模块图像处理------颜色空间处理之拜耳模式去马赛克函数demosaicing()
  • 网络套接字基础使用和概念
  • PaddleNLP 的文本分类项目
  • React--》掌握react组件库设计与架构规划
  • PyTorch 中mm和bmm函数的使用详解
  • SMT贴片制造流程关键环节解析
  • 科技趋势分析系统(BBC)技术全解
  • 通用前端框架项目静态部署到Hugging Face Space的实践指南
  • PHP实战:安全实现文件上传功能教程