How to detect inactive tab and fill it with color

心已入冬 提交于 2019-12-21 21:25:47

问题


How can I fill my website with color if tab is inactive? I would like to give screensaver like effect to my site if user move to another window. Can I do that with jQuery?


回答1:


Here is some basic code to get you going:

<script type="text/javascript"> 
document.onmousemove = resetTimer;
window.onload = function() {
    screenTimer = setTimeout(inactive, 2000);
}
function inactive(){
    // screen saver goes here
    document.body.style.backgroundColor = "black";
}
 function resetTimer(e) {
    // undo screen saver here
    document.body.style.backgroundColor = "white";
    // reset timer
    clearTimeout(screenTimer);
    screenTimer = setTimeout(inactive, 2000);
}
</script> 

Using jquery you could probably clean that up a bit, but this should give a simple foundation to build off of.

Basically, we keep calling the "start screensaver" every 2 seconds, but if you move your mouse it cancels the timer and starts it over. Note: setTimeout uses milliseconds so 1000 = 1 second.




回答2:


Use window.onfocus() and window.onblur() methods - see http://www.thefutureoftheweb.com/demo/2007-05-16-detect-browser-window-focus/ for demo



来源:https://stackoverflow.com/questions/3563489/how-to-detect-inactive-tab-and-fill-it-with-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!