在JavaScript中,获取当前焦点的元素可以使用document.activeElement
属性。这个属性返回当前文档中获得焦点的元素,如果没有元素获得焦点,则返回<body>
元素或者null
(如果文档没有加载完成)。
// 获取当前焦点元素
var focusedElement = document.activeElement;
// 打印当前焦点元素的标签名
console.log("当前焦点的元素是:", focusedElement.tagName);
document.activeElement
在文档加载完成之前可能返回null
。document.activeElement
可能返回<body>
元素。如果你遇到了无法获取当前焦点元素的问题,可以尝试以下步骤:
DOMContentLoaded
事件来确保这一点。document.addEventListener('DOMContentLoaded', function() {
var focusedElement = document.activeElement;
console.log("当前焦点的元素是:", focusedElement.tagName);
});
<input>
、<button>
、<a>
等元素。function openModal() {
var modal = document.getElementById('myModal');
modal.style.display = "block";
// 设置焦点到模态对话框内的某个元素
modal.querySelector('.modal-content input').focus();
}
通过这些方法,你可以更有效地获取和管理页面上的焦点元素。
领取专属 10元无门槛券
手把手带您无忧上云