滚动动画柜台

时间:2018-08-29 15:08:03

标签: javascript jquery comma

所以,我找到了一支很棒的笔Creative Animated Counter on Scroll,但我想知道如何格式化数字,如果数字超过一千则使用逗号。

function visible(partial) {
  var $t = partial,
    $w = jQuery(window),
    viewTop = $w.scrollTop(),
    viewBottom = viewTop + $w.height(),
    _top = $t.offset().top,
    _bottom = _top + $t.height(),
    compareTop = partial === true ? _bottom : _top,
    compareBottom = partial === true ? _top : _bottom;

  return ((compareBottom <= viewBottom) && (compareTop >= viewTop) && $t.is(':visible'));
}

$(window).scroll(function() {
  if (visible($('.count-digit'))) {
    if ($('.count-digit').hasClass('counter-loaded')) return;
    $('.count-digit').addClass('counter-loaded');

    $('.count-digit').each(function() {
      var $this = $(this);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.text()
      }, {
        duration: 5000,
        easing: 'swing',
        step: function() {
          $this.text(Math.ceil(this.Counter));
        }
      });
    });
  }
})

1 个答案:

答案 0 :(得分:0)

您要寻找的方法是toLocaleString。您可以在一个号码上调用它以获得所需的逗号。您只需要像这样更改step函数:

step: function() {
  $this.text(Math.ceil(this.Counter).toLocaleString());
}