[英]JavaScript / jQuery or something to change text every some seconds
I need JavaScript or jQuery something to change text every few seconds... without the user doing anything.我需要 JavaScript 或 jQuery 每隔几秒更改一次文本……用户无需执行任何操作。
Example:例子:
"Welcome" changes to "Salmat datang" changes to "Namaste", etc. after 3 seconds and loops back. “Welcome”变为“Salmat datang”,3 秒后变为“Namaste”等,然后循环返回。
As others have said, setInterval
is your friend:正如其他人所说,
setInterval
是你的朋友:
var text = ["Welcome", "Hi", "Sup dude"]; var counter = 0; var elem = document.getElementById("changeText"); var inst = setInterval(change, 1000); function change() { elem.innerHTML = text[counter]; counter++; if (counter >= text.length) { counter = 0; // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle } }
<div id="changeText"></div>
You may take a look at the setInterval
method.您可以查看
setInterval
方法。 For example:例如:
window.setInterval(function() {
// this will execute on every 5 seconds
}, 5000);
setInterval(function(){
alert('hello, do you have a beer?');
}, 1000);
where 1000 ms = 1 second.其中 1000 毫秒 = 1 秒。
You can use setInterval
to call a function repeatedly.您可以使用
setInterval
重复调用 function。 In the function you can change the required text.在 function 中,您可以更改所需的文本。
The list of texts to change between could be stored in an array, and each time the function is called you can update a variable to contain the current index being used.要更改的文本列表可以存储在一个数组中,每次调用 function 时,您都可以更新一个变量以包含正在使用的当前索引。 The value can loop round to
0
when it reaches the end of the array.当它到达数组的末尾时,该值可以循环到
0
。
See this fiddle for an example.有关示例,请参见此小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.