2016-11-17 46 views
0

我想有一個計數器,只激活實際上當屏幕上。我已經設法從我發現的其他例子中解決了這個問題。爲什麼在達到目標後倒計時?

HTML:

<div>Scroll Down</div> 
<span class="count">200</span> 

CSS:

div { 
    height:800px; 
    background:red; 
} 
h1 { 
    display:none; 
} 

的Javascript:

$(window).scroll(function() { 
    var hT = $('#scroll-to').offset().top, 
     hH = $('#scroll-to').outerHeight(), 
     wH = $(window).height(), 
     wS = $(this).scrollTop(); 
    console.log((hT - wH), wS); 
    if (wS > (hT + hH - wH)) { 
     $('.count').each(function() { 
      $(this).prop('Counter', 0).animate({ 
       Counter: $(this).text() 
      }, { 
       duration: 4000, 
       easing: 'swing', 
       step: function(now) { 
        $(this).text(Math.ceil(now)); 
       } 
      }); 
     }); 
    } 
}); 

DEMO:

https://jsfiddle.net/76d57vjL/

的問題是,它達到200,然後計數回落到0,但我希望它只是停留在200。我似乎無法找出什麼真正導致它雖然。

回答

1

的問題是,你創造了超過1個動畫,開始計數後,所以回到1,我有一個固定的標誌,但也許你能與高度的東西,檢查了這一點。

這裏了標誌的修復:https://jsfiddle.net/uc0av8fh/

var flag = true; 
$(window).scroll(function() { 
$('#scroll-to'); 
    var hT = $('#scroll-to').offset().top, 
     hH = $('#scroll-to').outerHeight(), 
     wH = $(window).height(), 
     wS = $(this).scrollTop(); 
    console.log((hT-wH) , wS); 
    if (wS > (hT+hH-wH)){ 
    $('.count').each(function() { 
     if(!flag) return; 
     //console.log(); 
     flag = false; 
     $(this).prop('Counter',0).animate({ 
      Counter: $(this).text() 
     }, { 
      duration: 4000, 
      easing: 'swing', 
      step: function (now) { 
       $(this).text(Math.ceil(now)); 
       return 1; 
      } 
     }); 
    }); 
    } 
}); 
+0

謝謝!爲什麼它不在這裏工作? https://jsfiddle.net/ys5x3du0/ – Fazy

+0

您需要將ID添加滾動向DIV。我在我的例子中添加了,因爲我認爲你真正的同事擁有它。 – Gaunt