There is a similar question here. But it doesn't work when a page is initially loaded because the blur event will not fire if for example the user opens the page开发者_如何学编程 in a new tab and it doesn't get focus.
So what would be the best way to do this?
For now, my temporary solution is to assume the tab is blurred when it loads and bind a function to the mouseover event of the document that will set it to focused. But that won't work if the user does not have their mouse on the page.
Borrowing from the code you linked to, set the default to blurred:
<div id="blurDiv"></div>
<script>
var updateStatus = (function() {
// Private stuff
var el = document.getElementById('blurDiv');
// The updateStatus function
return function (evt) {
evt = evt || window.event;
var evtType = evt.type;
var state;
// Determine state
if (evtType == 'load' || evtType == 'blur' || evtType == 'focusout' ) {
state = 'blurred';
} else {
state = 'focussed';
}
// Now do something...
el.innerHTML += '<br>' + state
};
})();
window.onload = updateStatus;
if (/*@cc_on!@*/false) { // check for Internet Explorer
document.onfocusin = updateStatus;
document.onfocusout = updateStatus;
} else {
window.onfocus = updateStatus;
window.onblur = updateStatus;
}
</script>
IE seems to fire lots of extra events, every time something gets focus, there is first a blur then a focus so clicking on things in the page has lots of spurious blur/focus pairs.
精彩评论