假设我有一个标题为"Hi I am a title“的网页,但在页面加载5秒后,它变成了"Hi I I am another title”,然后5秒后变成了"I am a title“,然后这种情况不断发生,请again.Can某人指导我如何实现这一点。我从w3schools.com上获取了一些在线教程。我真的很想这样做,但我甚至不知道从哪里开始。
发布于 2016-10-22 16:51:54
var i=0;
setInterval(function(){
var titles=['Hi everyone', 'Salut tout le monde', 'Cao svima'];//add more titles if you want
if(i===titles.length) {
i=0;
}
document.title = titles[i];
i++;
}, 5000);发布于 2016-10-22 16:53:09
这段代码中最复杂的部分是使用模运算来根据titles数组的长度获得当前迭代。
(ii++ % titles.length)我们增加迭代器的ii++,然后使用模数(除法余数)来计算迭代器的当前值。这将允许您根据需要使用任意多的标题。
const titles = [
'Hi I am a title',
'Hi I am another title',
'I am also a title'
]
function changeTitles(titles){
// save an iterator in a closure
let ii = 0
// update is run at the start
return (function update() {
// change the title
document.querySelector('title').textContent = titles[(ii++ % titles.length)]
// queue the function to be called in 5 seconds
setTimeout(update, 5000)
})()
}
changeTitles(titles)
发布于 2016-10-22 17:03:41
<!DOCTYPE html>
<html>
<head>
<title>hello</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var titles = ['title1', 'title 2', 'title 3'];
var timeInterval = 5000; /** interval between each titles **/
exec();
setInterval(function(){
exec();
}, timeInterval * titles.length);
function exec(){
$.each(titles, function(k, v){
setTimeout(function(){
$('title').html(v);
}, timeInterval * (k + 1));
});
}
});
</script>
</body>
</html>https://stackoverflow.com/questions/40190099
复制相似问题