我希望我的代码在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>
答案 0 :(得分:0)
这是因为你测试文字是否是&#39;你好&#39; (顺便说一下,我不确定“你好”之前的空间是否有用)如果是,请用“Rick and Morty”替换它,但如果没有替换它&#34; ........&#34;
第一次,它将是假的,因为你的文字将是&#34;你好&#34;而不是&#34;你好&#34;在H之前有一个空格,所以它将被替换为&#34; ........&#34;
第二次,你的文字将是&#34; .......&#34;这也不等于&#34;你好&#34;所以它将再次被&#34; .......&#34;等等替换。
如果您希望订单始终相同,请尝试此操作:
<script>
setInterval(function() {
$('h4').fadeOut(1000, function() {
var $this = $(this);
const current_text = $this.text();
const texts = ['Hello', '.....', 'Rick and Morty']
let new_text = ""
for( let i = 0; i < texts.Length; i++ )
{
if( current_text==texts[i] )
{
const n = i < texts.Length-1 ? i+1:0;
new_text = texts[n];
break;
}
}
$this.text(new_text);
$this.toggleClass('fade1');
$this.fadeIn(1000);
});
}, 3000);
</script>
答案 1 :(得分:0)
如果您检查$this.val()
以找到下一个,那么在到达....
时会遇到麻烦,因为Hello
或Rick and Morty
可以跟着。您必须存储来自“Hello&#39;”的最后一个打印值。和&#39; Rick and Morty&#39;为了推断出以下内容......&#39;
另一种解决方案是使用序列数组和存储下一个要显示的项的外部索引。递增索引每个循环并在达到序列长度时重置它。
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);