且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用jquery / javascript检测页面是背景还是前景?

更新时间:2022-05-10 08:23:08

我知道答案已被选中,但我想分享另一种方式。

I know that the answer has already been selected but I wanted to share another way.

你可以使用 hasFocus 文档上的方法,看它是否有焦点。没有理由设置自己的变量。

You can use the hasFocus method on the document to see if it has the focus. There is no reason to set your own variable.

以下是概念代码的一些证明。 jsFiddle位于底部。每隔3秒,它会检查窗口是否有焦点 - 显示真或假。

Here's some proof of concept code. jsFiddle is at the bottom. Every 3 seconds it will check if the window has focus or not–displaying true or false.

HTML:

<p>This will show if the document has focus every three seconds</p>
<button id="go">Go</button>
<button id="stop">Stop</button>

<ul id="active_log">
</ul>

CSS:

#stop { display: none; }

文档准备就绪内的Javascript:

Javascript inside on document ready:

var timeout = null;

var checkActive = function() {
    var isActive = window.document.hasFocus(),
        $activity = $("<li />").text(isActive.toString());

    $('#active_log').prepend($activity).find('li:nth-child(n+6)').fadeOut(function() {
        $(this).remove();
    });

    timeout = setTimeout(checkActive, 3000);
}

$('#go').click(function() {
    $(this).hide().siblings('button').show();
    checkActive();
});

$('#stop').click(function() {
    $(this).hide().siblings('button').show();
    clearTimeout(timeout);
    timeout = null;
});

http://jsfiddle.net/natedavisolds/2D7za/1/