2012-03-16 41 views
2

如果存在,我會根據圖像的alt屬性爲圖像標題設置一個小動畫片段jQuery只有先前的動畫完成時,jquery纔會在懸停動畫中添加延遲

它工作正常,但我有一個小問題。我想要一個delay懸停(slideUp)動畫,但只有如果以前slideIn動畫完全完成。在基本場景:

場景1:用戶將鼠標懸停圖像,字幕全動畫在用戶將鼠標懸停出來,動畫延遲(字幕原地踏步)2秒鐘,然後動畫出來。

場景2:用戶將鼠標懸停在圖像上,標題開始生成動畫,但用戶在完成之前懸停。動畫應該立即停止,並在的情況下生成動畫,而不會延遲

情況1完美地工作。情景2沒有。延遲發生在部分動畫元素滑出之前,這是不需要的。我可以看到我的代碼中存在缺陷,但似乎無法弄清楚如何解決它。

Fiddle,和當前的腳本:

$('.pv-inner').hover(function() { 

    var img = $(this).find('img:first'); 
    var text = img.attr('alt'); 

    if (text !== undefined) { 
     //remove any existing captions 
     $(this).find('.kppImageCaption').remove(); 

     //insert the new caption 
     img.after('<div class="kppImageText">' + text + '</div><div class="kppImageCaption"></div>'); 

     //animate it in 
     $(this).find('.kppImageCaption').stop().slideDown('slow').animate({ 
      opacity: 0.6 
     }, { 
      queue: false, 
      duration: 'slow', 
      complete: function() { 
       $(this).parent().find('.kppImageText').fadeTo(1000, 1); 
      } 
     }); 
    } 
}, function() { 

    //on hover out animate it out. Here is the problem. I only want the delay 
    //to occur if the above hover over animation completed - currently it delays 
    //in all cases. 
    $(this).find('.kppImageCaption, .kppImageText').stop().delay(2000).slideUp('slow', function() { 
     $(this).remove(); 
    }); 

}); 

編輯

Final working fiddle。可以幫助某個人在路上。

回答

1

創建變量,我們稱之爲var animationStatus = false 剛開始製作動畫之前,在complete功能設置animationStatus = true

(見jQuery的動畫文件)設置animationStatus = false

在你的函數,它是負責隱藏 - 創建如果聲明。如果animationStatus === false - 延遲。如果animationStatus === true - 沒有延遲。

祝你好運!

+0

謝謝我會試試這個 - 如果我使用這個腳本在頁面上有多個圖像,我假設他們會分享這個變量?我對js的範圍很殘酷。也想使用/檢測一個CSS類作爲標誌.. – 2012-03-16 15:08:21

+0

感謝您的幫助。我使用了與你建議的方法相同的方法,但是使用css類標誌來確保js範圍不會成爲問題,如果我在頁面上有多個帶字幕的圖像。最後的小提琴:http://jsfiddle.net/r4bzE/11/ – 2012-03-16 15:17:53

+0

很高興聽到這:)這也是爲什麼我試圖解釋一個想法,而不是提供一個工作解決方案(代碼)。愛看看人們是如何自己做的:) – MFix 2012-03-20 08:21:40