2017-06-24 64 views
-1

這是我的代碼,用於增加數字動畫。 Fiddle:如何使增加數字動畫僅在滾動上工作

代碼:

$('.Count').each(function() { 
 
    var $this = $(this); 
 
    jQuery({ 
 
    Counter: 0 
 
    }).animate({ 
 
    Counter: $this.text() 
 
    }, { 
 
    duration: 1000, 
 
    easing: 'swing', 
 
    step: function() { 
 
     $this.text(this.Counter.toFixed(1)); 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="Count">7.4</span> 
 

 
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> 
 

 
<span class="Count">3.7</span><br/> 
 
<span class="Count">9.1</span><br/> 
 
<span class="Count">5.6</span>

現在,我怎麼只增加上滾動多少?我試圖使用count ::之前,但它沒有工作。我不是專業

回答

1

不知道這是否是你想要的

countEach() 
$(window).on('scroll', function(e) { 
    countEach() 
}) 

function countEach() { 
    $('.count').each(function() { 
     if (showOnScreen(this) && $(this).attr('show') != 'false') { 
      console.log($(this).text()) 
      console.log($(this).attr('show')) 
      $(this).attr('show', 'false') 
      numberAnimate(this) 
     } else if (!showOnScreen(this)) { 
      $(this).attr('show', 'true') 
     } 
    }) 
} 

function showOnScreen(target) { 

    if ($(window).scrollTop() + $(window).height() >= $(target).offset().top) 
     return true; 
    else 
     return false; 
} 

function numberAnimate(target) { 
    var $this = $(target); 
    jQuery({ 
     Counter: 0 
    }).animate({ 
     Counter: $this.text() 
    }, { 
     duration: 1000, 
     easing: 'swing', 
     step: function() { 
      $this.text(this.Counter.toFixed(1)); 
     } 
    }); 
} 

Js fiddle

+0

感謝你的努力兄弟,但。此代碼有2個問題: 1)該計數器只工作1次,我希望它再次工作,如果他們有更多的計數器下行。 2.)它只能在滾動中工作。如果已在屏幕上,則在頁面加載時不起作用。 看到這個小提琴https://jsfiddle.net/1m25rdw1/6/ –

+0

嘿我做了一些改變,你可以做出你想要的基於這個變化:p –