【问题标题】:Find focused element in document with many iframes在包含许多 iframe 的文档中查找焦点元素
【发布时间】:2014-08-21 07:07:01
【问题描述】:
我有一个包含多个 iframe 的文档。 iframe 都有文本区域和文本框。如何找出整个文档中的焦点元素(带有光标的元素)?我需要一个方法(或属性),它将在所有 iframe 中搜索并返回带有光标的文本区域或文本框。
document.ActiveElement 在控制台中为我提供了整个文档的正文。
【问题讨论】:
标签:
javascript
jquery
focus
【解决方案1】:
我已经为你做了。使用此功能,您可以在网页或 iframe 中激活元素。该函数检查活动元素的位置并返回它:
/**
* Return the active element in the main web or iframes
* @return HTMLElement
**/
function getActiveElement() {
var focused = false;
// Check if the active element is in the main web or no
if( document.body === document.activeElement ||
document.activeElement instanceof HTMLIFrameElement ){
// Search in iframes
$('iframe').each(function(){
var element = this.contentWindow.document.activeElement;
// If there is a active element
if( element !== this.contentWindow.document.body ){
focused = element;
return false; // Stop searching
}
});
}
else focused = document.activeElement;
return focused; // Return element
}
您可以看到一个 jsfiddle 示例在:http://jsfiddle.net/tgrywLz7/5/
更新:
更好!使用新功能,您可以在具有多级 iframe 且没有 jQuery! 的网页中获取活动元素:
/**
* Retrieve active element of document and preserve iframe priority MULTILEVEL!
* @return HTMLElement
**/
var getActiveElement = function( document ){
document = document || window.document;
// Check if the active element is in the main web or iframe
if( document.body === document.activeElement
|| document.activeElement.tagName == 'IFRAME' ){
// Get iframes
var iframes = document.getElementsByTagName('iframe');
for(var i = 0; i<iframes.length; i++ ){
// Recall
var focused = getActiveElement( iframes[i].contentWindow.document );
if( focused !== false ){
return focused; // The focused
}
}
}
else return document.activeElement;
return false;
};
实际操作:http://jsfiddle.net/tgrywLz7/9/
【解决方案2】:
现在是 2020 年,这是用于检查其他文档上下文中的活动元素的最佳 Google 搜索结果之一。
将其更新为更简单,并检查影子根。 :)
/**
* Return the active element of a page, regardless of shadow root or iframe window.
* @returns {HTMLElement}
*/
function getActiveElement(element = document.activeElement) {
const shadowRoot = element.shadowRoot
const contentDocument = element.contentDocument
if (shadowRoot && shadowRoot.activeElement) {
return getActiveElement(shadowRoot.activeElement)
}
if (contentDocument && contentDocument.activeElement) {
return getActiveElement(contentDocument.activeElement)
}
return element
}