2016-12-08 72 views
1

我想讓我的代碼在JavaScript中使用setInterval函數淡入淡出文本。目前它只會運行我的第一段文本,然後不斷重複最後一遍。我不確定它是JavaScript還是我的html。JavaScript setInterval函數只能在文本中淡出一次

<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> 
+1

代碼工作:https://jsfiddle.net/uj7c9cu5/。你期待有不同的結果嗎? –

+0

是的,但它說'你好'後它只能重複點。我試圖讓它說'你好','....','裏克和莫蒂' - 不需要他們以任何特定的順序,只是希望他們都出現。對不起,我不是最擅長解釋我想要的。 –

+0

預期的序列到底是什麼?你好 - > ... - >裏克和莫蒂 - >你好 - > ...? –

回答

0

如果選中$this.val()找到下一個到達的時候....,因爲它可以跟任何Hello否則你會惹上麻煩Rick and Morty。您必須存儲'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); 

小提琴:https://jsfiddle.net/d82btd8m/1/

0

這是因爲你測試,如果文字是「你好」(順便說一下,我不知道,如果之前的空間的「你好」是故意的),如果是,通過「瑞克和莫蒂更換',但如果不是替換爲「........」

第一次,它將是假的,因爲您的文本將是「你好」,而不是「你好」 ,所以它會替換爲「........」

第二次,你的文本將是「.......」這也不等於「你好」,所以它會再次替換爲「.......」等。

如果你想以總是相同試試這個:

<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>