javascript 当网页获得焦点时的事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4651193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:26:01  来源:igfitidea点击:

Event when a web page gets focused

javascriptjqueryhtmljavascript-events

提问by Shay Erlichmen

Google Reader has a nice feature that when you switch to the web page from a different web page (giving the page focus) it will show you the updates there were accumulated while the page was unfocused.
Quick question #1: How do they do that?

谷歌阅读器有一个很好的功能,当你从不同的网页切换到网页时(给页面焦点),它会向你显示页面未聚焦时累积的更新。
快速问题#1:他们是怎么做到的?

I figure that they might be binding to the mouse move events + keyboard events since I don't know any out of the box event that gives you that ability.

我认为它们可能会绑定到鼠标移动事件 + 键盘事件,因为我不知道任何能够为您提供这种能力的开箱即用事件。

Googling for that is a nightmare (focus, tab, web page, user).

谷歌搜索是一场噩梦(焦点、标签、网页、用户)。

Quick question #2: Is there some package out there that gives me that ability?

快速问题#2:是否有一些软件包可以赋予我这种能力?

I'm putting the jQuery tag as a beacon for all the web developers ninjas out there, but I don't really care about the framework (as long as its Javascript)

我把 jQuery 标签作为所有网络开发忍者的灯塔,但我并不真正关心框架(只要它的 Javascript)

回答by PeeHaa

Try using jQuery's focusand blurfunctions:

尝试使用 jQueryfocusblur函数:

$(window).focus(function() {
   console.log('welcome (back)');
});

$(window).blur(function() {
   console.log('bye bye');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click in and out of this frame to test the focus and blur functions.

回答by jAndy

Use focusin(focus) and focusout(blur) on the documentobject:

在对象上使用focusin(focus) 和focusout(blur) document

$(document).bind('focus', function() {
   console.log('welcome (back)');
}).bind('blur', function() {
   console.log('bye bye');
});

回答by Juan Mendes

I tested in FF and document.onfocusis called when I switch to that window.

我在 FF 中进行了测试,并document.onfocus在切换到该窗口时被调用。