我正在使用一个用下面的代码更改标题的函数,每当窗口处于焦点时,它必须停止更改。
//Set to true on first load
var window_focus = true;
$(window).focus(function () {
return window_focus = true;
})
.blur(function () {
return window_focus = false;
});
// THE CHANGE FUNCTION
function doHighlightNow (){
var highlightTimer = null;
var oldTitle = document.title;
function doHighlight() {
if (window_focus){
stopHighlight();
}
var doBlink = function() {
document.title = "Title one"
setTimeout(function(){
document.title = "Title two";
}, 1000);
}
doBlink();
}
function stopHighlight() {
document.title = 'stopped';
clearInterval(highlightTimer);
}
highlightTimer = setInterval(function(){doHighlight(nickname) }, 2500);
}
现在每次触发doHightlightNow()
时都会更改标题,windows_focus
不是true
,否则会清除间隔。
现在我想让窗口再次处于焦点时直接触发stopHighlight()
,如果触发了doHighlightNow()
,那么最佳解决方案是什么。
我现在必须是这样的,
$(window).on("click", "focus",function(){
trigger stopHighlightnow();
});
但我不确切知道如何提供这个,我希望有人可以帮助我。
答案 0 :(得分:1)
你能做的是,
var highlightTimer = null; // Create it outside the function
// So you can stop it outside the function
function doHighlightNow (){
var oldTitle = document.title;
function doHighlight() {
//No need for this inside the function
//if (window_focus){
//stopHighlight();
//}
var doBlink = function() {
document.title = "Title one"
setTimeout(function(){
document.title = "Title two";
}, 1000);
}
doBlink();
}
// Neither need this anymore inside the function
//function stopHighlight() {
//document.title = 'stopped';
//clearInterval(highlightTimer);
//}
highlightTimer = setInterval(function(){doHighlight(nickname) }, 2500);
}
$(window).on("focus", function(){
if (window_focus){
document.title = 'stopped';
clearInterval(highlightTimer);
}
});
答案 1 :(得分:0)
你有更好的方法来做你想做的事情,你有一个内置事件:
document.addEventListener("visibilitychange", function() {
if(document.visibilityState === 'hidden') {
document.title = "Title one";
} else {
document.title = "Title two";
}
});