有什么方法可以检测到该窗口当前在 IE8 中处于活动状态吗? [英] Is there any way to detect that window is currently active in IE8?

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

问题描述

有什么方法可以在 IE8 中检测窗口当前处于活动状态(显示在活动选项卡/窗口上)?

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

我知道有像 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.

我相信对于这种普通的用例,必须有一些简单、优雅的解决方案.

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.

它通过使用 Page Visibility API 来实现a> 在支持它的地方,并在旧浏览器中回退到良好的旧 focusblur.

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

这个插件只提供了两个自定义事件供您使用:showhide.当页面可见性状态发生变化时,会触发相应的事件.

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天全站免登陆