反击没有达到价值

时间:2017-08-23 12:51:30

标签: javascript jquery

我使用以下代码作为计数器。我注意到计数器并不总能达到更高的值(特别是5500) - 调整速度并不能解决问题。有谁知道问题可能是什么?



startCounter();

function startCounter() {
  var hT = $('.value').offset().top,
    hH = $('.value').outerHeight(),
    wH = $(window).height();
  if ($(window).scrollTop() > hT + hH - wH) {
    $(window).off("scroll", startCounter);
    $('.value').each(function() {
      var $this = $(this);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.text()
      }, {
        duration: 3500,
        easing: 'linear',
        step: function() {
          $this.text(Math.ceil(this.Counter) + '');
        }
      });
    });
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="value">5500</span>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

我添加了完整的回调,与步骤回调完全相同。关于步骤的事情是它被执行来操作补间,这意味着它不会在动画的末尾被调用(也就是当你达到想要的值时)

startCounter();

function startCounter() {
  var hT = $('.value').offset().top,
    hH = $('.value').outerHeight(),
    wH = $(window).height();
  if ($(window).scrollTop() > hT + hH - wH) {
    $(window).off("scroll", startCounter);
    $('.value').each(function() {
      var $this = $(this);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.text()
      }, {
        duration: 3500,
        easing: 'linear',
        step: function() {
          $this.text(Math.ceil(this.Counter) + '');
        },
        complete(){
          $this.text(Math.ceil(this.Counter) + '');
        }
      });
    });
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="value">5500</span>