检查窗口是否有焦点 [英] Check if window has focus

查看:95
本文介绍了检查窗口是否有焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查用户是否有焦点窗口,我现在正在这样做:

I need to check if the user has windows on focus, I'm currently doing this:

var isonfocus=true;  
window.onblur = function(){  
  isonfocus=false;  
}  
window.onfocus = function(){  
  isonfocus=true;  
}

每当我需要检查用户是否有焦点窗口我只是执行 if(isonfocus == true)

And whenever I need to check if the user has the windows on focus I just do if(isonfocus==true).

问题:如果用户在页面加载前失去焦点,即使我执行
if(isonfocus == true)它将返回true,即使窗口不在焦点上,并且将var定义为false var isonfocus = false; 将执行相反的操作。

Problem: if the user loses focus before the page loads, even if I do if(isonfocus==true) it will return true, even though the window is not on focus, and defining the var to false var isonfocus=false; will do the reverse.

有人能帮帮我吗?谢谢。

Can someone help me? Thanks.

更新

想象一下PTC(付费点击)网站,当你点击要查看广告,大多数网站会验证用户是否实际看到了广告客户网站(有焦点)(焦点丢失)。

这与我需要的类似,我需要一种方法来验证是否用户在焦点上有窗口(包含iframe)。

要获得焦点,用户可以点击iframe,文档或选项卡。

请注意这个需要适用于所有主流浏览器。

UPDATE
Imagine a PTC (Paid-To-Click) site, when you go and click an ad to view, most sites verify if the user is actually seeing the advertiser site (has focus) or not (lost focus).
This is similar with what I need, I need a way to verify if the user has the window (which contains an iframe) on focus.
And to gain focus, the user could click the iframe, document or on the tab.
And please note that this needs to work on all major browsers.

推荐答案

var has_focus = true;

function loading_time() {
    $(":focus").each(function() {
      if($(this).attr("id")=="iframeID") has_focus = true;
    });

    if(has_focus==true) alert('page has focus');
    else alert('page has not focus');

    setTimeout("loading_time()", 2000);
}

window.onblur = function(){  
    has_focus=false;  
}  
window.onfocus = function(){  
    has_focus=true;  
}

$(window).load(function(){
    setTimeout("loading_time()", 2000);
});

为了提高效率,你需要 var has_focus = false; 并让用户点击页面上的某个位置。

To make it more efficient, you need to var has_focus = false; and make the user click somewhere on the page.

这篇关于检查窗口是否有焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆