2015-04-18 24 views
1

我正在检查当前选项卡/窗口是否关注或不执行某些特定任务。以下功能正确地工作,以检测焦点时我切换标签,但当标签打开,我打开软件(音乐播放器/ Windows文件夹)保持选项卡活动/打开,该功能仍然认为窗口/选项卡为重点!我试图实现的情况是检测窗口/选项卡由于打开应用程序失去焦点/软件在当前集中的窗口/选项卡上。如果您提供基于我的代码的答案,jsfiddle将会很棒!活动窗口检测

$(document).ready(function() { 

     var hidden, change, vis = { 
      hidden: "visibilitychange", 
      mozHidden: "mozvisibilitychange", 
      webkitHidden: "webkitvisibilitychange", 
      msHidden: "msvisibilitychange", 
      oHidden: "ovisibilitychange" /* not currently supported */ 
     };    
    for (hidden in vis) { 
     if (vis.hasOwnProperty(hidden) && hidden in document) { 
      change = vis[hidden]; 
      break; 
     } 
    } 
    if (change) 
     document.addEventListener(change, onchange); 
    else if (/*@[email protected]*/false) // IE 9 and lower 
     document.onfocusin = document.onfocusout = onchange 
    else 
     window.onfocus = window.onblur = onchange; 

    function onchange (evt) { 
     evt = evt || window.event; 
     if (evt.type == "focus" || evt.type == "focusin") 
      window_focus = true; 
     else if (evt.type == "blur" || evt.type == "focusout") 
      window_focus = false; 
     else   
      window_focus = this[hidden] ? false : true; 
    } 

}); 

框架:

<frameset rows="130,*" style="border: 1px #CC3333" noresize="noresize" "> 
<frame name="showcountframe" src="https://jsfiddle.net/nvobhaor/1/" scrolling=no marginheight="2" marginwidth="2" noresize="noresize"> 
<frame name="showcontframe" src="showcontframe.html" marginheight="0" marginwidth="0" noresize="noresize"> 
</frameset><noframes></noframes> 
+0

那么这就是'visibilitychange'事件是如何工作的。提出错误或实施建议。到目前为止,我唯一能想到的就是在document.hidden为false时检查是否空闲 –

回答

0

你可以使用window.onfocuswindow.onblur这个,而不是代码墙。它受到所有主要浏览器的支持,并且完美适用于您想要的目的。例如,它会检测您更改标签的时间,或者像您所说的那样打开另一个应用程序。

例子:

window.onfocus = function() { 
    console.log('Focused'); 
}; 

window.onblur = function() { 
    console.log('Not focused'); 
}; 
+0

浏览器兼容性如何? – query

+0

它应该无处不在。 (在http://jscc.info/上确认,并在http://www.w3schools.com/jsref/event_onfocus.asp上看到) –

+0

如果我想将此代码与我的代码合并,该怎么办?我应该像这样添加else if(evt.type ==“onblur”) window_focus = false; ? – query