javascript Jquery 每 2 秒用数组中的单词替换文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32445323/
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
Jquery replace text every 2 seconds with words from an array
提问by Marc Ster
I want to replace a text in a span with the id "words" with words from an array every 2 seconds
我想每 2 秒用一个数组中的单词替换 id 为“words”的文本
$('#words').delay(1000).fadeOut(1000);
$(this).delay(3000).text('word2').fadeIn(1000);
$(this).delay(5000).text('word3').fadeIn(1000);
$(this).delay(7000).text('word4').fadeIn(1000);
This is what I've got but obviously it stops working after 7 seconds.. how can I repeat this? Or even use an array to hold the words.. Thank you!
这就是我所拥有的,但显然它在 7 秒后停止工作......我怎么能重复这个?或者甚至使用数组来保存单词..谢谢!
回答by Praveen Kumar Purushothaman
You can use setInterval()
to do this:
您可以使用以下setInterval()
方法执行此操作:
$(function () {
count = 0;
wordsArray = ["Beta", "Gamma", "Delta", "Alpha"];
setInterval(function () {
count++;
$("#word").fadeOut(400, function () {
$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
});
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="word">Alpha</div>
回答by Stewartside
This is easily achievable using just Vanilla JS (normal JS without jQuery) as shown below.
这很容易使用 Vanilla JS(没有 jQuery 的普通 JS)来实现,如下所示。
Create a setInterval()
loop to run every 2 seconds and randomize each time to get a different array element.
创建一个setInterval()
循环,每 2 秒运行一次,每次随机化以获得不同的数组元素。
var names = ['test1', 'test2', 'test3', 'test4'];
setInterval(function() {
var rand = Math.floor(Math.random() * 4);
document.getElementById("name").innerHTML = names[rand];
}, 2000);
<div id="name">test</div>
If you want to have a fading effect (as mentioned in a comment) your best option will be to use jQuery.
如果您想要淡入淡出效果(如评论中所述),您最好的选择是使用 jQuery。
回答by Meloman
Here is a working code to swap between two sentences on a website FR -> EN -> FR -> ...
这是一个可以在网站上的两个句子之间交换的工作代码 FR -> EN -> FR -> ...
jsbased on @praveen-kumar-purushothaman solution :
JS基础上@普利文-库马尔- purushothaman的解决方案:
count = 0;
wordsArray = [
'Texte en fran?ais incluant des <strong>balises html</strong>.',
'Text in french including <strong>html tags</strong>.'
];
setInterval(function () {
count++;
$("#mytext").fadeOut(300, function() {
$(this).html(wordsArray[count % wordsArray.length]).fadeIn(500);
});
}, 5000);
htmlwith first text displayed in french :
html,第一个文本以法语显示:
<h1 id="mytext">
Texte en fran?ais incluant des <strong>balises html</strong>.
</h1>
Hope it helps some.
希望能帮到一些人。