javascript - 为什么达到目标后就倒计时了?

标签 javascript jquery jquery-animate

我想要一个只有在实际出现在屏幕上时才会激活的计数器。我已经成功地将它与我发现的其他示例结合在一起。

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

关于javascript - 为什么达到目标后就倒计时了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40657141/

相关文章:

javascript - 如何显示帖子提要中最喜欢的帖子?

javascript - 如何将 base64 转换为 html 文件?

jquery - 使用 jquery animate 方法在容器 div 周围移动框 div

javascript - HTML 输入文件 onchange 不会为不同的文件触发第二次

javascript - 继续在 Typescript 和 ActionScript 3 之间打字

javascript - Kendo 网格列显示/隐藏 80 多个列出现问题

javascript - 用于拖放绘图应用程序的 Canvas 与 jQuery

javascript - 如何使用 jquery ajax 传递数据

javascript - 为什么慢速 jQuery 动画断断续续?

gwt - GWT 中类似 jQuery 的平滑动画