2010-05-21 169 views
4

我有以下功能,當我調用時顯示一條消息給用戶一段時間(在我的情況下爲5秒)。在此期間,如果我再次調用該函數來顯示另一條消息,實際上它應該隱藏,然後再以新消息再出現5秒。如何啓動/停止/重新啓動jQuery動畫

下面我的代碼會發生什麼,我稱之爲顯示消息的函數。然後,讓我們在第4秒鐘說,我再次打電話來顯示另一條消息,新消息顯示1秒。

我需要以某種方式 - 重置 - 時間,但無法弄清楚如何。試圖停止動畫,檢查元素是否可見並隱藏它,如果是的話,還有很多其他的東西。我相信解決方案是一個簡單的鏈接問題,但不能正確解決。所以任何幫助將不勝感激!

function display_message(msgType, message) { 

    var elem = $('#ur_messagebox'); 

    switch (msgType) { 
     case 'confirm': 
      elem.addClass('msg_confirm'); 
      break; 

     case 'error': 
      elem.addClass('msg_error'); 
      break; 
    } 

    elem.html(message); 
    elem.show().delay(5000).fadeOut(1000); 
} 

在此先感謝...

回答

6

總之,你不能使用.delay()爲你想要的。這只是一個關於下一個隊列項目,you can see the source heresetTimeout()包裝,重要的部分:

return this.queue(type, function() { 
     var elem = this; 
     setTimeout(function() { 
      jQuery.dequeue(elem, type); 
     }, time); 
    }); 

所以這只是排隊setTimeout()被執行時,從隊列在隊列中的下一個項目並執行它。所以,發生了什麼事是你添加一個延遲,甚至與.stop(true).clearQueue(),當你排隊.fadeOut()後你補充說回相同fx隊列,所以當setTimeout()結束在5秒鐘內,它的抓新的淡出排隊並執行它。

你需要setTimout()手動清除,因爲jQuery的核心沒有這個內置的,是這樣的:

function display_message(msgType, message) { 
    var mb = $('#ur_messagebox') 
      .addClass(msgType === 'confirm' ? 'msg_confirm' : 'msg_error') 
      .html(message) 
      .stop(true, true).fadeIn(); 
    if(mb.data('delay')) clearTimeout(mb.data('delay')); 
    mb.data('delay', setTimeout(function() { mb.fadeOut(1000); }, 5000)); 
} 

You can see a working demo here

+2

完美答案!非常感謝你! – 2010-05-24 14:21:53

0

試試這個。

elem.stop().show().delay(5000).fadeOut(1000); 
+0

這不起作用。之前嘗試過。顯示新的消息,但在第一條消息的5秒鐘內剩下的一段時間內。 – 2010-05-21 18:25:12

0

我得到CSS衝突,因爲你永遠不添加其他之前刪除味精類,所以我清除那些除了elem.removeClass('msg_confirm msg_error');來解決這個問題:

function display_message(msgType, message) { 

    var elem = $('#ur_messagebox'); 
    elem.removeClass('msg_confirm msg_error'); 

    switch (msgType) { 
     case 'confirm': 
      elem.addClass('msg_confirm'); 
      break; 

     case 'error': 
      elem.addClass('msg_error'); 
      break; 
    } 

    elem.stop().css({opacity:1}).clearQueue(); 
    elem.html(message); 
    elem.show().delay(5000).fadeOut(1000); 
} 
elem.stop().css({opacity:1}).clearQueue();

所以我停止在添加消息並重新啓動隊列之前,重置不透明度以防止它在淡出過程中並清除隊列。我測試了這個,它應該適合你。

+0

不!這似乎也不起作用。我越深入研究這個問題,我越會遇到更多有延遲功能問題的人。在這裏閱讀評論http://api.jquery.com/delay/ – 2010-05-21 19:27:42

+0

啊,有趣的是,我只測試了某些情況,但它並不適用於所有情況。將繼續擺弄。 – mVChr 2010-05-21 19:45:39

0

我重新啓動動畫是這樣的:(但不知道它是否完全正確)

$(element).stop()。clearQueue(); (元素).delay(20).animate({...});

1

由於Nick指出:

總之,你不能使用.delay()你想要的東西。

但有一個簡單的解決方法:而不是使用.delay(x)只是使用.fadeTo(x,1)

基本上,這會褪色到完全不透明,但由於消息框已經處於完全不透明狀態,因此除了延遲以下動畫之外,此操作不會執行任何操作,只能延遲x毫秒。優點是.fadeTo()可以使用.stop(true)停止/中止。

0

如果使用jQuery,只是再次重新啓動前完成當前的動畫:

tooltip.finish();// set a defined start for animation 
tooltip.show(); 
tooltip.delay(4000).fadeOut(1500); 
相關問題