假设我有一个网页,标题为“Hi I am a title”,但加载后5秒钟后变成“Hi I am another title”,再过5秒钟后又变成“I am also a title”,这一过程不断重复。能否请有经验的人指导我如何实现这一效果?我在w3schools.com上学习了一些在线教程,但我甚至不知道从哪里开始。
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);
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)
<!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>
<html>
<script type="text/javascript">
messages = [ "one", "two", "three" ]
function rotateTitle() {
index = 0
setInterval(function() {
if (messages.length == index) {
index = 0
}
document.title = messages[index]
index++
}, 5000)
}
</script>
<body onLoad="rotateTitle()">
</body>
</html>
这样的代码对你有用。
HTML代码(重新加载div以查看效果:P)
<div id="page_title"></div>
<br>
<span id="text-reload">Reload</span>
JS
// custom jquery plugin loadText()
$.fn.loadText = function( textArray, interval ) {
return this.each( function() {
var obj = $(this);
obj.fadeOut( 'slow', function() {
var elem = textArray[0];
obj.empty().html( elem );
textArray.shift();
textArray.push(elem);
obj.fadeIn( 'fast' );
});
timeOut = setTimeout( function(){ obj.loadText( textArray, interval )}, interval );
$("#text-reload").click( function(){
if( !obj.is(':animated') ) { clearTimeout( timeOut ); obj.loadText( textArray, interval );} // animation check prevents "too much recursion" error in jQuery
});
});
};
$(document).ready(function() {
var helloArray = ["Hi I am a title", "Hi I am another title", "I am also a title", "more", "and more", "and even more", "aloha", "see ya!"];
$('#page_title').loadText( helloArray, 5000 ); // ( array, interval )
document.title = $('#page_title').text();
});
试一下这个
<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>
array[iterator%array.length]
。 - Mike B