gpt4 book ai didi

javascript - 在具有许多 iframe 的文档中查找焦点元素

转载 作者:行者123 更新时间:2023-11-30 07:04:40 26 4
gpt4 key购买 nike

我有一个包含多个 iframe 的文档。 iframe 都有文本区域和文本框。如何找出整个文档中的焦点元素(光标所在的元素)是什么?我需要一个方法(或属性)来搜索所有 iframe 并返回其中包含光标的文本区域或文本框。

document.ActiveElement 在控制台中为我提供了整个文档。

最佳答案

我已经为你做了。使用此功能,您可以使元素在网页或 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/

关于javascript - 在具有许多 iframe 的文档中查找焦点元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25420219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com