Javascript / jQuery或每隔一秒更改文本的东西

问题描述 投票:16回答:4

需要JavaScript或jQuery每隔一秒就能改变文本...用户做任何事情。

例:

“欢迎”更改“Salmat datang”在3秒后变为“Namaste”等并循环回来。

javascript jquery jquery-plugins dom-events
4个回答
30
投票

正如其他人所说,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>

4
投票

你可以看看setInterval方法。例如:

window.setInterval(function() {
    // this will execute on every 5 seconds
}, 5000);

3
投票
setInterval(function(){
   alert('hello, do u have a beer ?');
}, 1000);

其中1000ms = 1秒;


2
投票

您可以使用setInterval重复调用函数。在该功能中,您可以更改所需的文本。

要更改的文本列表可以存储在数组中,每次调用该函数时,您都可以更新变量以包含当前使用的索引。当值到达数组末尾时,该值可以循环到0

有关示例,请参阅this fiddle

© www.soinside.com 2019 - 2024. All rights reserved.