是否有窗口获取焦点的浏览器事件? [英] Is there a browser event for the window getting focus?
问题描述
有没有办法在我点击浏览器并给予关注时,运行一次方法?然后当浏览器失去焦点然后重新获得焦点再次再次运行该方法时。
Is there a way that when I click on my browser, and give it focus, to run a method once? And then when the browser loses focus and then gets the focus back to again run that method only once, again.
推荐答案
你可以在窗口
对象上附加 focus
和 blur
事件处理程序跟踪窗口是否获得或失去焦点(请参阅 http://jsfiddle.net/whQFz/ 以获取一个简单的示例)。 window
适用于当前浏览器上下文(因此可以是窗口,选项卡,框架等)。
You can attach focus
and blur
event handlers on the window
object to track if the window gets or loses focus (see http://jsfiddle.net/whQFz/ for a trivial example). window
applies to the current browser context (so that could be a window, a tab, a frame, etc.).
注意:每次窗口获得焦点时,焦点
事件都会触发,模糊
事件会在每次失去焦点时触发。将焦点从窗口移开的一个示例是 alert
窗口。如果您尝试在 onfocus
事件处理程序中发出警报,您将获得无限循环警报!
Note : The focus
event will fire every time the window gets focus and the blur
event will fire every time it loses focus. An example of something that takes focus away from the window is an alert
window. If you try to alert in an onfocus
event handler you'll get an infinite loop of alerts!
// Set global counter variable to verify event instances
var nCounter = 0;
// Set up event handler to produce text for the window focus event
window.addEventListener("focus", function(event)
{
document.getElementById('message').innerHTML = "window has focus " + nIndex;
nCounter = nCounter + 1;
}, false);
// Example of the blur event as opposed to focus
// window.addEventListener("blur", function(event) {
// document.getElementById('message').innerHTML = "window lost focus"; },
// false);
这篇关于是否有窗口获取焦点的浏览器事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!