我希望我的代码使用 JavaScript 中的 setInterval 函数淡入和淡出文本。目前,它只会运行我的第一段文本,然后一遍又一遍地重复最后一段。我不确定它是 JavaScript 还是我的 html。
<div class="col-md-3">
<h3 id="RickQuotes" class="text-center">Rick "C137" Sanchez</h3><br />
<h4 class="fade1">Hello</h4>
</div>
<script>
setInterval(function() {
$('h4').fadeOut(1000, function() {
var $this = $(this);
$this.text($this.text() == ' Hello' ? 'Rick and Morty' : '.......');
$this.toggleClass('fade1');
$this.fadeIn(1000);
});
}, 3000);
</script>
最佳答案
如果您检查 $this.val()
来查找下一个,那么在到达 ....
时您会遇到麻烦,因为它后面可以是任一你好
或瑞克和莫蒂
。您必须存储“Hello”和“Rick and Morty”的最后打印值,以便推断出“...”后面的内容
另一个解决方案是使用一个序列数组和一个存储下一个要显示的项目的外部索引。每次循环递增索引,并在达到序列长度时重置索引。
var index = 0;
setInterval(function() {
$('h4').fadeOut(1000, function() {
var $this = $(this);
var sequence = ['Hello','....', 'Rick and Morty', '....'];
index = index == sequence.length ? 0 : index;
$this.text(sequence[index++]);
$this.toggleClass('fade1');
$this.fadeIn(1000);
});
}, 2000);
fiddle :https://jsfiddle.net/d82btd8m/1/
关于JavaScript setInterval 函数仅淡入文本一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41045681/