在有许多iframe的文档中查找焦点元素
Find focused element in document with many iframes
我有一个包含多个iframe的文档。iframe都有文本区和文本框。如何找出整个文档中的焦点元素(光标所在的元素)是什么?我需要一个方法(或属性),这将在所有的iframe搜索,并返回文本区或文本框与光标在其中。
文档。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/
现在是2020年,这是在其他文档上下文中检查活动元素的谷歌结果之一。
将其更新为更简单,并检查阴影根。:)
/**
* 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
}
相关文章:
- keyup事件处理程序更改焦点不适用于快速键入
- 单击时将焦点更改为元素
- 正在全局范围中查找JavaScript函数
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 后焦点更改为IE 11中的地址栏,而不是转移到表单中的下一个控件
- 在不使用jquery的情况下查找页面中的所有锚点并附加函数
- es6 相当于下划线查找位置
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 如何在不传递此信息的情况下查找被调用的元素
- Lodash 从值数组中查找数组中的值
- 在IE9中的输入字段中输入焦点最近按钮
- 如何使用JavaScript查找1和N之间的所有数字的总和
- 使用RegExp查找url中的字符
- 查找元素高度,包括边距
- 遍历 DOM 以查找哪个元素具有焦点
- Jquery/Javascript:点击即可查找光标/焦点字段
- 如何使用Jquery正确查找焦点
- 在有许多iframe的文档中查找焦点元素
- 正在查找文本区域上的焦点事件源