Jquery每2秒用数组中的单词替换文本

Jquery replace text every 2 seconds with words from an array

本文关键字:单词 替换 文本 数组 2秒 Jquery      更新时间:2023-09-26

我想每隔2秒将id为"words"的span中的文本替换为数组中的单词

$('#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);

这是我得到的,但显然它在7秒后停止工作。我该怎么重复呢?或者甚至使用数组来保存单词…谢谢你!

您可以使用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>

这很容易实现,只使用香草JS(普通JS没有jQuery),如下所示。

创建一个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>

如果你想有一个褪色的效果(如在评论中提到的),你最好的选择是使用jQuery。

这是一个在网站上的两个句子之间切换的工作代码FR -> EN -> FR ->…

js基于@praveen-kumar-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);

html第一个文本以法语显示:

<h1 id="mytext">
    Texte en français incluant des <strong>balises html</strong>.
</h1>

希望能有所帮助。