2017-09-06 72 views
0

我有一個時間表,其示出了根據所選擇的日期不同的內容。日期可以通過點擊時間軸來選擇,或者用鼠標滾輪滾動。 我有一些附加到每個內容的動畫,爲了有不同的內容元素淡出/淡出效果,爲此,我使用嵌套動畫和回調。拆離事件的工作僅在第一次使用jQuery

我不能做的,是等待一個動畫結束,下一個開始之前,如果滾動快速度。 或者,更好的,我拆開滾動事件的動畫功能的開始,並重新將其固定,作爲最後animate函數調用的回調:該作品僅在第一次,但不是隨後滾動。

有什麼想法?

功能檢測滾動:

 //detect mouse scrolling and determine the direction 
     function detectScroll() { 
      $('.events-content').first().bind('mousewheel', function (e) { 
       var delta = e.originalEvent.wheelDelta; 
       if (delta > 0) { 
        jumpToEvent('prev'); 
       } else { 
        jumpToEvent('next'); 
       } 
      }); 

      //firefox 
      $('.events-content').first().on('DOMMouseScroll', function (e) { 
       var delta = e.originalEvent.detail; 
       if (delta < 0) { 
        jumpToEvent('prev'); 
       } else if (delta > 0) { 
        jumpToEvent('next'); 
       } 
      }); 
     } 

功能detatching滾動

function detachScroll(){ 
      console.log('detach'); 
      $('.events-content').first().unbind('mousewheel'); 
      $('.events-content').first().off('DOMMouseScroll'); 
     } 

功能的動畫,jumpToEvent函數調用時,選擇正確的內容顯示:

//display correct content depending on the selected date 
function updateVisibleContent(event, eventsContent) { 

    var visibleContent = ...., selectedContent =....; 

    detachScroll(); 

    visibleContent.find('....').each(function() { 
     $(this).animate({ 
      opacity: 0 //hide current content 
     }, 600, function() { 

      visibleContent.removeClass('selected'); 
      selectedContent.attr('class', 'selected'); 

      //now show the next content, with 3 subsequent steps (Showing only one for the sake of readability) 
      selectedContent.find('...').first().animate({ 
       opacity: 1 
      }, 500, function() { 
        detectScroll(); 
      });    
     }); 
    });  
} 
+0

那麼使用'.stop()'來停止舊的動畫呢? – Deckerz

+0

您是否嘗試使用文檔準備功能註冊您的動畫功能,以便在頁面委託您想要的任何事件時完成動畫並啓動新的動畫功能? –

+0

@Deckerz我曾嘗試使用.stop(),在動畫功能的開始,而不是分離(),但我有一個類似的行爲,它的工作原理是第一次,然後如果我繼續滾動快,下內容全部顯示在一起。順便說一下,這不是我想要的行爲,我更願意「等待」內容完全顯示。任何線索? – sissy

回答

1

你需要每一個有生命的呼叫前加.stop(),這確保了沒有未決/正在進行動畫調用一個動畫時。

0

您是否嘗試過的jQuery deferred-object,它是等待異步函數來完成的一種方式。

function doAnimations(domElement, i) { 
    var dfd = jQuery.Deferred(); 

    $(domElement[i]).animate({ 
    //do somthing 
    }, 600, function() { 
    dfd.resolve 
    }) 

    return dfd.promise(); 
} 

//And this is how you can itterate tru items 
(function rec(i){ 
    if(i >= numbers of itterations) { 
    console.log('End') 
    return false 
    } 

    doAnimations(domElement, i).done(function(){ 
    rec(++i) 
    }) 
})(0) 
+0

我見過類似的解決方案,https://stackoverflow.com/questions/18360963/在這裏重複一個嵌套動畫在jQuery中,但我認爲它不能解決我的問題。我會試一試,如果我沒有得到我的例子的工作,但現在看起來很好。 – sissy

相關問題