如何使一段Javascript工作,只有当用户是在不同的选项卡

How to make a piece of Javascript work only when the user is on a different tab?

本文关键字:选项 用户 Javascript 何使一 工作      更新时间:2023-09-26

我有下面的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>

我希望它的工作只有当用户打开了一个不同的标签,以"吸引"他/她回到我的网站。当他/她在我的网站上,我希望这个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。这是个好主意吗?还有其他建议吗?我真的很喜欢打破常规。

请尝试下面的脚本。

<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>