影响Iframe的$(窗口).blur事件

Jir*_*ico 8 javascript iframe jquery dom

我想检测用户何时离开我的页面(例如打开一个新标签),这样我就可以停止倒计时了.我用它做了:

$(window).blur(function() {
 //stop countdown
});
Run Code Online (Sandbox Code Playgroud)

但是我的页面中有一个Iframe,当用户点击它时,倒计时也会停止,但我不希望当有人点击Iframe时执行上述事件.

任何的想法?

更新,我正在尝试更多,基于iframe上的这个答案点击事件?:

iframeDoc = $('iframe').contents().get(0);
$(iframeDoc).click(function(){
   //maybe remove blur event?
});
Run Code Online (Sandbox Code Playgroud)

更新:Tim B解决方案有效:

$(window).blur(function () {
// check focus
if ($('iframe').is(':focus')) {
    // dont stop countdown
}
else {
    // stop countdown
}                
});
Run Code Online (Sandbox Code Playgroud)

现在,我必须在每次调用模糊事件时从Iframe中移除焦点,否则如果用户在关注Iframe后更改制表符,倒计时将不会停止.我尝试使用上述条件:

if ($('iframe').is(':focus')) {
    // dont stop countdown
    $("iframe").blur()
    $(window).focus();
}
Run Code Online (Sandbox Code Playgroud)

但它没有用.任何的想法?

Tim*_*mes 5

一种解决方案是检查 iframe 是否具有焦点,然后不停止计时器。例如

$(window).blur(function () {
    // check focus
    if ($('iframe').is(':focus')) {
        // dont stop countdown
    }
    else {
        // stop countdown
    }                
});
Run Code Online (Sandbox Code Playgroud)

现在这将起作用,但是如果您的 iframe 在用户更改选项卡时具有焦点,则倒计时不会停止。因此,在这种情况下,您需要考虑一个优雅的解决方案,将焦点从 iframe 转移。例如,如果用户在 iframe 内单击,则会立即将焦点移回父窗口。

编辑 - 更新答案以包含额外的 iframe 功能

好的,所以我一直在玩这个。现在我不知道您的 iframe 中有什么内容,但是您可以向其中添加一些代码,这些代码基本上在单击时将焦点发送回父窗口中的对象。例如

在您的 iFrame 中

<script>
    $(function () {
        $(document).click(function () {
            // call parent function to set focus
            parent.setFocus();
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

在您的主页

<script>

    function setFocus() {
        // focus on an element on your page.
        $('an-element-on-your-page').focus();
    }

    $(function () {

        $(window).focus(function (e) {
            // bind the blur event
            setBindingEvent();
        });

        var setBindingEvent = function () {
            // unbind
            $(window).unbind('blur');
            $(window).blur(function () {
                // check focus
                if ($('iframe').is(':focus')) {
                    // unbind the blur event
                    $(window).unbind('blur');
                }  
                else {
                    // stop countdown
                }                
            });
        };

        setBindingEvent();

    });
</script>
Run Code Online (Sandbox Code Playgroud)

这将允许您单击 iframe,将焦点设置回主页,然后停止倒计时。