Javascript 文本幻灯片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19070927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Text Slideshow
提问by RMi Flores
I am trying to add text into a div using JavaScript and/or jQuery and then have that text change to different text every 10 seconds -- so somewhat like a slideshow of just plain text. Here's my code:
我正在尝试使用 JavaScript 和/或 jQuery 将文本添加到 div 中,然后让该文本每 10 秒更改为不同的文本——有点像纯文本的幻灯片。这是我的代码:
<div id="textslide"><p></p></div>
<script>
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
var counter = 0;
while (true) {
if (counter > 4) counter = 0;
document.getElementById('textslide').firstChild.innerHTML = quotes[counter];
counter++;
setTimeout( // not sure what to put here, 500); // Want to delay loop iteration
}
</script>
回答by
HTML:
HTML:
<div id="textslide"><p></p></div>
JavaScript/jQuery:
JavaScript/jQuery:
var quotes = [
"quote1",
"quote2",
"quote3",
"quote4",
"quote5",
];
var i = 0;
setInterval(function() {
$("#textslide").html(quotes[i]);
if (i == quotes.length) {
i = 0;
}
else {
i++;
}
}, 10 * 1000);
回答by Sergio
Here is a suggestion with plain JS
这是一个简单的 JS 建议
function loop() {
if (counter > 4) counter = 0;
document.getElementById('textslide').firstElementChild.innerHTML = quotes[counter];
counter++;
setTimeout(loop, 500);
}
loop();
Demo here
演示在这里
If you want to use jQueryyou can use this: $('#textslide p:first').text(quotes[counter]);
如果你想使用jQuery,你可以使用这个:$('#textslide p:first').text(quotes[counter]);
Demo here
演示在这里
回答by Moe Assaad
Instead of while, use:
而不是while,使用:
setInterval(function () {
//do your work here
}, 10000);
回答by Kobbe
Use a function and call it on body onload
使用一个函数并在 body onload 上调用它
<html>
<head>
<script>
var counter = 0;
function changeText()
{
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
if (counter > 4)
{
counter = 0;
}
document.getElementById("textslide").innerHTML = quotes[counter];
setTimeout(function(){changeText()},10000);
counter ++;
}
</script>
</head>
<body onload="changeText();">
<p id="textslide"></p>
</body>
</html>