为什么达到目标后会倒计时?

Why is this counting down after reaching the target?

我想要一个只有在实际出现在屏幕上时才会激活的计数器。我已经设法从我发现的其他示例中将其拼凑在一起。

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));
                }
            });
        });
    }
});

演示:

https://jsfiddle.net/76d57vjL/

问题是,它达到 200,然后倒计时到 0,但我希望它保持在 200。不过我似乎无法弄清楚到底是什么原因造成的。

问题是您正在创建超过 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;
          }
      });
    });
   }
});