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

Find focused element in document with many iframes

本文关键字:查找 焦点 元素 文档 许多 iframe      更新时间:2023-09-26

我有一个包含多个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
}