我有以下javascript,每隔五秒就会一次又一次地更改网页标题。
<script>
var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
var N = titleArray.length;
var i = 0;
setInterval(func,5000);
function func(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
</script>
我希望它仅在用户打开不同的标签页时才能使用,以便吸引&#34;他/她回到我的网站。虽然他/她在我的网站上,我希望这个javascript停止工作,所以网页的标题就是我在标题标签中写的。
这里是我想要的摘要。
<script>
if (the user is not on this tab but has opened and is using a different tab)
{the javascript I have mentioned above};
elce {nothing so the title tags work};
</script>
P.S:这是个好主意吗?还有其他建议吗?我真的很想开箱即用。
答案 0 :(得分:0)
请尝试使用以下脚本。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var isActive;
window.onfocus = function () {
isActive = true;
};
window.onblur = function () {
isActive = false;
};
// test
var titleArray = ["TITLE-1","TITLE-2","TITLE-3","TITLE-4"];
var N = titleArray.length;
var i = 0;
function changeTitle(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
setInterval(function () {
if(window.isActive !== true){
changeTitle();
}
}, 1000);
</script>