我网页中的 IFrame 触发模糊事件

IFrame inside my webpage triggering blur event

我的网页上有一个倒计时以及一个 IFrame。倒计时将在 $(window).blur 停止并在 $(window).focus 开始。当我点击 IFrame 时,它​​会触发模糊事件并停止倒计时。我已经通过以下代码行解决了这个问题。

 $(window).blur(function () {
  if (document.activeElement.nodeName == "IFRAME") {
    //Continue timer
    else {
        //Stop timer
    }
 });

但是,当我在点击 IFrame 内部后立即点击 window 外部时,Blur 事件没有被触发。因为除非触发焦点事件,否则模糊事件不会在模糊事件之后触发。

我提到了类似的主题 - $(window).blur event affecting IframeHow can I capture the blur and focus of the entire browser window?

还有其他想法吗?

更新- 我采用了另一种方法,让我又向前迈进了一步。以下代码是新方法

$(window).on('focus', function () {
                            //Coundown runs
                    }).on('blur', function () {
                            //Coundown stops
                    });;

 $(document).ready(function () {
                var iframe = document.getElementById("iframeID");
                            $(iframe.contentWindow).on('focus', function (){
                                    //Coundown runs
                            }).on('blur', function () {
                                    //Coundown stops
                            });
                    });

此代码将在 iframe 焦点上进行倒计时 运行,并在 iframe 模糊时停止。

但是,我在这种方法中面临的问题是当 "scr" 未在 Iframe 中加载时倒计时工作正常。如果 "scr" 在 Iframe 中加载,则 Iframe 的焦点和模糊事件不会绑定,并且 Iframe 单击时倒计时停止。

对此有什么想法吗?

我认为问题在于,一旦内容加载到您的 iframe 中,您的浏览器就会将其与 window 隔离(出于安全考虑)。

您可以使用 Window.postMessage() 在主 window 和 iframe 之间传递事件。

看看Window postmessage