2017-06-14 95 views
0

如何顯示div 2秒,然後在無限循環中隱藏它4秒?我使用jQuery的animate()函數,因爲我也想使用CSS轉換。jQuery顯示div 2秒,然後在循環中隱藏4秒

function animatedText() { 
    setTimeout(function() { 
     $('.text').animate({ opacity: 1 }, 200, function() { 
      setTimeout(function() { 
       $('.text').animate({ opacity: 0 }, 200); 
      }, 1800); 
     }); 
    }, 3800); 
} 
setInterval(animatedText(), 6000); 

這裏是我的小提琴:https://jsfiddle.net/od6gm8t3/

+2

你'setInterval'不運行任何東西,因爲號召'animatedText'不返回任何東西。如果應該每6秒調用一次'animatedText',那麼你需要編寫'setInterval(animatedText,6000)'。而不是使用間隔和超時,你應該使用jQuery的'延遲'功能和動畫的結束回調。 –

+0

我明白了。謝謝! – Plastik

回答

1

我希望這會幫助你。請檢查下面的代碼。

function animatedText() { 
 
    $('.text').animate({ opacity: 1 }, 200, function() { 
 
      setTimeout(function() { 
 
       $('.text').animate({ opacity: 0 }, 200); 
 
      }, 2000); 
 
    }); 
 
    setTimeout(function() { 
 
     animatedText(); 
 
    },6000); 
 
} 
 
animatedText();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<i class="text">Animated Text</i>

+0

謝謝!這幾乎是我需要的。問題是隻要我調用函數就會顯示div。我的意思是它不等待4秒,但我想我可以在窗口加載時調用setTimeout函數內的函數。對? – Plastik

+0

你能告訴我你的代碼嗎,所以我可以幫助你更好。 –

+0

我的意思是:https://jsfiddle.net/od6gm8t3/1/有沒有更好的方法在函數內部做到這一點?您的代碼只要功能名爲 – Plastik