【问题标题】:How to make a piece of Javascript work only when the user is on a different tab?仅当用户在不同的选项卡上时,如何使一段 Javascript 工作?
【发布时间】:2016-11-02 09:00:20
【问题描述】:

我有以下 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.S:这是个好主意吗?还有其他建议吗?我真的很喜欢跳出框框思考。

【问题讨论】:

标签: javascript jquery title titlebar


【解决方案1】:

请尝试以下脚本。

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

【讨论】:

  • 感谢您的好意和努力,但仍然存在问题。当我刷新页面时,我会得到我想要的标题标签中写的标题。当我打开另一个选项卡时,您的脚本开始工作并且标题开始改变,这又是我想要的。但是在那之后,当我回到该站点时,脚本只是暂停了,而不是获取原始标题(在标题标签之间),我得到了在另一个选项卡中显示的最后一个标题。我根本没有得到原始的倾斜返回
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多