有没有办法在IE8中检测到该窗口当前是否处于活动状态? [英] Is there any way to detect that window is currently active in IE8?

查看:95
本文介绍了有没有办法在IE8中检测到该窗口当前是否处于活动状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在IE8中检测到窗口当前处于活动状态(正在活动标签/窗口中显示)?

Is there any way to detect that the window is currently active (is being shown on active tab/window) in IE8?

我知道有类似<的事件code> onfocusin / onfocus - 但这不是一个完美的解决方案,因为窗口也必须获得焦点才能触发事件 - 所以当用户只是在不触摸窗口的情况下切换标签时,这不起作用。

I know there are events like onfocusin/onfocus - but this is not a perfect solution, since the window must also receive focus for the event to be fired - so this does not work when the user just switches the tabs without touching the window itself.

我认为必须有一些简单,优雅的解决方案,适用于这种普通用途 - case。

I believe there has to be some simple, elegant solution for such ordinary use-case.

推荐答案

我编写了一个jQuery插件来执行此操作: http://mths.be/visibility 它为您提供了一个非常简单的API,允许您在页面的可见性状态发生变化时执行回调。

I’ve written a jQuery plugin that does this: http://mths.be/visibility It gives you a very simple API that allows you to execute callbacks when the page’s visibility state changes.

使用 页面可见性API

It does so by using the the Page Visibility API where it’s supported, and falling back to good old focus and blur in older browsers.

演示: http://mathiasbynens.be/demo/jquery-visibility

此插件只提供两个自定义事件供您使用: show 隐藏。当页面可见性状态发生变化时,将触发相应的事件。

This plugin simply provides two custom events for you to use: show and hide. When the page visibility state changes, the appropriate event will be triggered.

您可以单独使用它们:

$(document).on('show', function() {
  // the page gained visibility
});

...和...

$(document).on('hide', function() {
  // the page was hidden
});

由于大部分时间都需要这两个活动,所以最好选择使用活动地图。这样,您可以一次绑定两个事件处理程序:

Since most of the time you’ll need both events, your best option is to use an events map. This way, you can bind both event handlers in one go:

$(document).on({
  'show': function() {
    console.log('The page gained visibility; the `show` event was triggered.');
  },
  'hide': function() {
    console.log('The page lost visibility; the `hide` event was triggered.');
  }
});

该插件将检测浏览器是否本机支持页面可见性API,并公开此信息作为布尔( true / false )在 $。support.pageVisibility

The plugin will detect if the Page Visibility API is natively supported in the browser or not, and expose this information as a boolean (true/false) in $.support.pageVisibility:

if ($.support.pageVisibility) {
  // Page Visibility is natively supported in this browser
}

这篇关于有没有办法在IE8中检测到该窗口当前是否处于活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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