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

问题描述 投票:8回答:3

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

$(window).blur(function() {
 //stop countdown
});

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

任何的想法?

更新,我正在尝试更多,基于这个答案Click-event on iframe?

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

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

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

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

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

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

javascript jquery dom iframe
3个回答
4
投票

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

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

现在这可以工作,但是如果你的iframe在用户更改标签时有焦点,倒计时就不会停止。因此,在这种情况下,您需要考虑一个优雅的解决方案,将焦点从iframe之前移开。例如,如果用户在iframe中单击,则将焦点内移到父窗口。

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

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

在你的iFrame中

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

在您的主页面中

<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>

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


1
投票

由于iframe的隔离,在内部点击它会被视为父项的模糊。如果可以使用ajax引入iframe的内容,那将是更好的选择。


0
投票

我也有同样的问题。在我的情况下,我无法通过CMS访问iframe页面及其加载,我无法更改所有iframe。我的计时器用setInterval()计数,并在间隔内,我检查iframe。

const focus = function() {
	// timer start
	isBlured = 0;
};

const blur = function() {
  // timer stop
  isBlured = 1;
}

window.addEventListener('focus', focus);
window.addEventListener('blur', blur);

function intervalFunction() {
 
  var activeELM = document.activeElement.tagName;

  if (isBlured == 0 || activeELM == "IFRAME"){
      // dont stop countdown
    	var stopIframe = $('iframe').blur();     
  }
  
}
© www.soinside.com 2019 - 2024. All rights reserved.