Javascript计数器开始滚动

时间:2019-06-14 06:09:54

标签: javascript

我需要此计数器从滚动开始,而不是从滚动开始。有可能吗?

function startCounter(){
    $('.counter').each(function (index) {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 2000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.round(now*10)/10);
            }
        });
    });
}   

startCounter();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="counter">92.2</span>

2 个答案:

答案 0 :(得分:3)

从滚动事件侦听器内部调用函数

window.addEventListener('scroll', function(event) {
  // you could do startCounter(); here
  // maybe you want to check the event or the scroll position (window.scrollY)
  // maybe you pass the event to the startCounter(event) function
  console.log('scroll is happening, window.scroll position is:', window.scrollY)
});
<div style="height:10000px;width:200px;background-color:orange">just a big div to let the scroll appear</div>

有关滚动事件的更多信息,请参见:https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event

答案 1 :(得分:1)

这将为您做到。

window.addEventListener('scroll', function(e) {
    startCounter();
});