2014-08-30 66 views
0

我有這方面的工作JS提琴:http://jsfiddle.net/4v2wK/我該如何使這個動畫觸發滾動?

// Animate the element's value from x to y: 
$({someValue: 40000}).animate({someValue: 45000}, { 
    duration: 3000, 
    easing:'swing', // can be anything 
    step: function() { // called on every step 
     // Update the element's text with rounded-up value: 
     $('#el').text(commaSeparateNumber(Math.round(this.someValue))); 
    } 
}); 

function commaSeparateNumber(val){ 
    while (/(\d+)(\d{3})/.test(val.toString())){ 
     val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); 
    } 
    return val; 
} 

現在我想修改它,以便當用戶通過DIV滾動,不一定盤旋在它它時纔會觸發,但在div中可見他或她的屏幕。說這個div在一個長頁面的底部,當用戶到達那裏時,動畫結束了,他們錯過了整個節目。

+0

你可以使用inview(https://github.com/protonet/jquery.inview)或寫一些你自己的東西。檢查vieport的大小,改變它的大小,並檢查滾動位置,然後你知道該元素是否在視圖 – caramba 2014-08-30 20:24:35

+0

,所以你希望當用戶到達目標(div)時開始倒計時?或者只要用戶達到目標就想讓計數開始和結束? – ProllyGeek 2014-08-31 00:33:26

+0

我希望當它們到達那裏時開始,它的結局並不重要,但是開始的時候。謝謝! – 2014-09-01 03:05:04

回答

0

這段代碼會在您的div頂部超過250px時觸發動畫。

isScrolledIntoView(); 
$(window).scroll(function() { 
    isScrolledIntoView(); 
}); 
function isScrolledIntoView(){ 
    $('.class').each(function(){ // add the class of the divs you want trigger on scroll over 
     var $this = $(this).attr("id"); 
     var docViewTop = $(window).scrollTop(); 
     var docViewBottom = docViewTop + $(window).height(); 

     var elemTop = $(this).offset().top; 
     var elemBottom = elemTop + $(this).height(); 

     if ((elemTop >= docViewTop) && (((docViewBottom-250) >= elemTop))){ 
      // trigger your animation here 
      // with $this as a selector 
     } 
    })