使用 <TITLE> 标签加载多个不同的文本字符串

Using <TITLE> tag to load multiple different text string

我看到一些网站(即 http://www.legworkstudio.com/)的标签会定期更改,我认为这是通过 Javascript 完成的,但我没有看到任何类型的文档一个动作。

我不相信 document.title 会为此工作,但也许我误解了如何正确使用它。

有人见过这样的事情或如何最好地做到这一点吗?


基本上在 HTML 中每隔几秒就会这样:

<title>Title 1</title>

几秒后

<title>Title 2</title>

然后再过几秒

<title>Title 3</title>

您应该使用window setInterval 方法,然后使用选择器修改您的标题元素内容

来自 W3school 文档: https://www.w3schools.com/jsref/met_win_setinterval.asp

我认为 document.title 可以正常工作。试试这个:

var titles = ["Title1", "Title2", "Title3"];
var currentTitle = 0;
setInterval(function(){
    document.title = titles[currentTitle];
    if (currentTitle < titles.length - 1) {
        currentTitle++;
    } else {
        currentTitle = 0;
    }
}, 3000);

如果将此脚本添加到您的页面,它应该每三秒将页面标题更改为 titles 数组的下一个元素,无限循环回到数组的开头。

要更改更改之间的时间量,只需将 3000 更改为您希望更改之间的毫秒数。

要在任何时候停止循环,您可以使用clearInterval()

这能解决您的问题吗?

除了write之外,document中还有很多方法和属性。在这种情况下,您可以使用 title 属性.

访问和修改标题

有了这个和 timeout/interval 你循环标题做这样的事情:

var titles = ["Title 1", "My second title", "yay! third title shown!"];
setInterval(function() {
    document.title = titles.shift(); // Get the first element in the array and remove it.
    titles.push(document.title); // Push the element to the end of the array
}, 5000); // Milliseconds to loop

我有点喜欢codegolf,所以你可以这样做:P:

setInterval(function() {
    titles.push(document.title = titles.shift()); // Get the first element in the array, remove it, assign it to title and push it back to the end of the array.
}, 5000);