如果用户滚动回该部分,我该如何再次启动我的滚动计数器?

How do I start my scroll counter again if the user scrolls back to the section?

我制作了一个动画计数器,它会在您滚动进入视图后开始计数。如何在用户滚动回计数器时重新启动计数器?

我相信这会是一些我还不知道的简单事情。感谢您提供的任何帮助,非常感谢。

var a = 0;

$(window).scroll(function() {
  var oTop = $('#counter').offset().top - window.innerHeight;
  
  if (a == 0 && $(window).scrollTop() > oTop) {
    $('.counter-value').each(function() {
      var $this = $(this),
        countTo = $this.attr('data-count');
        
      $({
        countNum: $this.text()
      }).animate({
        countNum: countTo
      }, {
        duration: 2000,
        easing: 'swing',
        step: function() {
          $this.text(Math.floor(this.countNum));
        },
        complete: function() {
          $this.text(this.countNum);
          //alert('finished');
        }
      });
    });

    a = 1;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section class="numbers">
  <div class="container" id="counter">
    <h6 class="red-title">BY THE NUMBERS</h6>
    <h2 class="stats-heading">We’ll always measure up to your expectations</h2>

    <div class="numbers-box">
      <h1 class="counter-value" data-count="50">0</h1>
      <h6>years of experience</h6>
    </div>

    <div class="numbers-box">
      <h1 class="counter-value" data-count="37">0</h1>
      <h6>countires supplied</h6>
    </div>

    <div class="numbers-box">
      <h1 class="counter-value" data-count="128">0</h1>
      <h6>group automation employees</h6>
    </div>
  </div>
</section>

这个怎么样?

https://codepen.io/jonolayton/pen/MWmLJze

您可能需要 fiddle 以使其准确触发...我也在 CodePen 中编辑了一些 CSS,所以请在那里查看。

此外 - 它仅在计数已经停止时重新启动。否则它会变得很烦人。

var runAlready;
var counting;

function startCounter(a) {
  runAlready = true;
  counting = true;
  $('.counter-value').each(function() {
    var $this = $(this);
    $this.text(a);
    countTo = $this.attr('data-count');
    $({
      countNum: $this.text()
    }).animate({
      countNum: countTo
    }, 
    {
      duration: 2000,
      easing: 'swing',
      step: function() {
        $this.text(Math.floor(this.countNum));
      },
      complete: function() {
        $this.text(this.countNum);
        counting = false;
      }
    });
  })
}

$(window).scroll(function() {
  var oTop = $('#counter').offset().top;
  var a = 0;
  if (!runAlready && $(window).scrollTop() > oTop || !counting && $(window).scrollTop() < oTop) {
    startCounter(a);
  }
});