是否有窗口获得焦点的浏览器事件?

新手上路,请多包涵

有没有一种方法,当我点击我的浏览器并给它焦点时,运行一个方法一次?然后当浏览器失去焦点然后再次获得焦点时再次运行该方法一次。

原文由 Rod 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 567
2 个回答

您可以附加 focusblur --- 对象上的事件处理程序 window 对象以跟踪窗口是否获得焦点或失去焦点(参见 http:// jswqhnetFz / / 举个简单的例子)。 window 适用于当前浏览器上下文(因此可以是窗口、选项卡、框架等)。

注意: focus 事件将在每次窗口获得焦点时触发,而 blur 事件将在每次失去焦点时触发。将焦点从窗口移开的示例是 alert 窗口。 如果您尝试在 onfocus 事件处理程序中发出警报,您将获得无限循环的警报!

 // 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 " + nCounter;
    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);

原文由 Daniel Vandersluis 发布,翻译遵循 CC BY-SA 4.0 许可协议

$(document).ready(function() { $(window).one("focus", SomeFocusMethod); } );

var SomeFocusMethod = function()
{
    // do stuff
    $(window).one("blur", SomeBlurMethod);
}

var SomeBlurMethod = function()
{
    // do stuff
    $(window).one("focus", SomeFocusMethod);
}

原文由 Brett Weber 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题