jquery 检查窗口是否有焦点

5w9g7ksd  于 2023-06-05  发布在  jQuery
关注(0)|答案(7)|浏览(400)

我需要检查用户是否有窗口的焦点,我目前这样做:

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

每当我需要检查用户是否聚焦了窗口时,我只需执行if(isonfocus==true)
问题:如果用户在页面加载之前失去焦点,即使我做了if(isonfocus==true),它也会返回true,即使窗口没有焦点,将var定义为false var isonfocus=false;会做相反的事情。
有人能帮帮我吗谢谢

更新

想象一个PTC(付费点击)网站,当你点击一个广告来查看时,大多数网站都会验证用户是否真的看到了广告商网站(有焦点)或没有(失去焦点)。
这与我所需要的类似,我需要一种方法来验证用户是否将窗口(包含iframe)置于焦点上。
为了获得焦点,用户可以点击iframe,文档或标签。
请注意,这需要在所有主要浏览器上工作。

fgw7neuy

fgw7neuy1#

使用hasFocus方法:

if (document.hasFocus()) {
  // ...
}

如果您的页面上有iframe,则需要单独检查它们:

function isFocused() {
  return document.hasFocus() || document.getElementById('iframe').contentWindow.document.hasFocus();
}
mlnl4t2r

mlnl4t2r2#

您可以使用document.visibilityState,它将是'visible''hidden',以了解页面是否处于焦点中。

llmtgqce

llmtgqce3#

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;并让用户点击页面上的某个地方。

hm2xizp9

hm2xizp94#

此主题中的信息太旧。继续用途:document.hasFocus()。现在它将适用于您需要的所有浏览器。
浏览器兼容性:https://developer.mozilla.org/en-US/docs/Web/API/Document/hasFocus#browser_compatibility

lxkprmvk

lxkprmvk5#

如果你不关心Opera的支持,你可以使用document.hasFocus()方法得到更好的结果。参见here了解更多信息。

pexxcrt2

pexxcrt26#

**跨浏览器jQuery解决方案!**以下插件将通过您的标准测试,适用于各种版本的IE,Chrome,Firefox,Safari等。并相应地建立声明的方法。它还涉及以下问题:

  • 计时器!
  • Onblur|.blur/onfocus|.focus“duplicate”调用
  • 窗口通过选择备用应用程序(如Word)而失去焦点
    • 这往往是不可取的,因为,如果你有一个银行页面打开,它的 onblur 事件告诉它屏蔽页面,那么如果你打开计算器,你不能看到页面了!
  • 页面加载时不触发

使用非常简单:

$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
});

//  OR Pass False boolean, and it will not trigger on load,
//  Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
}, false);

//  OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
//  (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
$.winFocus({
    blur: function(event) {
        console.log("Blur\t\t", event);
    },
    focus: function(event) {
        console.log("Focus\t\t", event);
    }
});

//  OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
    console.log("Blur\t\t", event);
},
function(event) {
    console.log("Focus\t\t", event);
});

New&improvedversion,madeforbothvanillaandjQueryfoundhere!

/*    Begin Plugin    */
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$.winFocus.methods.onChange.call(document,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);
/*    End Plugin      */

// Simple example
$(function() {
	$.winFocus(function(event, isVisible) {
		$('td tbody').empty();
		$.each(event, function(i) {
			$('td tbody').append(
				$('<tr />').append(
					$('<th />', { text: i }),
					$('<td />', { text: this.toString() })
				)
			)
		});
		if (isVisible) 
			$("#isVisible").stop().delay(100).fadeOut('fast', function(e) {
				$('body').addClass('visible');
				$(this).stop().text('TRUE').fadeIn('slow');
			});
		else {
			$('body').removeClass('visible');
			$("#isVisible").text('FALSE');
		}
	});
})
body { background: #AAF; }
table { width: 100%; }
table table { border-collapse: collapse; margin: 0 auto; width: auto; }
tbody > tr > th { text-align: right; }
td { width: 50%; }
th, td { padding: .1em .5em; }
td th, td td { border: 1px solid; }
.visible { background: #FFA; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>See Console for Event Object Returned</h3>
<table>
    <tr>
        <th><p>Is Visible?</p></th>
        <td><p id="isVisible">TRUE</p></td>
    </tr>
    <tr>
        <td colspan="2">
            <table>
                <thead>
                    <tr>
                        <th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </td>
    </tr>
</table>
fjaof16o

fjaof16o7#

如果用户的浏览器窗口处于活动状态,但刚刚点击了刷新按钮(或url栏等),document.hasFocus()会告诉你该窗口未激活。
但是,您可以调用window.focus()并查看是否实际触发了focus事件。如果是,则浏览器仍处于聚焦/活动状态。

const windowHasFocus = function () {
  if (document.hasFocus()) return true
  let hasFocus = false

  window.addEventListener('focus', function () {
    hasFocus = true
  })
  window.focus()

  return hasFocus
}

相关问题