是否可以检测浏览器窗口何时处于活动/非活动状态
我确实尝试过:
$(window).on('focus', function(){
console.log(1);
});
$(window).on('blur', function(){
console.log(2);
});
但它似乎只有在用户点击窗口时才能正常工作。 但是当用户点击例如时显示2。浏览器地址栏。
我想要实现的是检测当前标签何时处于活动状态。
如何改进此代码?
答案 0 :(得分:2)
活动表示标签可见时。但是如果你想知道用户的鼠标是否直接在页面上,你可以使用它:
<html onmouseenter="document.getElementById('h1').innerHTML = 'active'"onmouseleave="document.getElementById('h1').innerHTML = 'not active'">
<body style="width:100%;height:100px">
<h1 id="h1">not active</h1>
</body>
</html>
&#13;
编辑:使用网页可见性API:
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
}
else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
}
else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
}
else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
function handleVisibilityChange() {
if (document[hidden]) {
//Not visible, Do whatever
}
else {
//Visible
}
}
if (typeof document.addEventListener === "undefined" ||
typeof document[hidden] === "undefined") {
alert("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
}
else {
document.addEventListener(visibilityChange, handleVisibilityChange, false);