【问题标题】:Adding commas to animated counting function在动画计数功能中添加逗号
【发布时间】:2017-04-19 18:58:47
【问题描述】:

我已经尝试了所有可以在网上找到的关于此的内容,但它们似乎都处理的是静态数字,而不是动画数字。

是否可以通过修改此函数将逗号添加到我的值中?

$('.counter').each(function() {
        var $this = $(this),
            countTo = $this.attr('data-count');

        $({ countNum: $this.text()}).animate({
            countNum: countTo
        },

        {

        duration: 500,
        easing:'linear',
        step: function() {
            $this.text(Math.floor(this.countNum));
        },
        complete: function() {
            $this.text(this.countNum);
              //alert('finished');
        }

    }); 

【问题讨论】:

  • 好吧,你们今天想成为有趣的人和语法纳粹。你会读javascript吗?如果您不了解此脚本将计数从 0 设置为 html 数据属性中定义的数字,那么您可能无法回答我的问题。
  • @JSum,编辑其他用户的语法和清晰度问题是 SO 工作方式的一个成熟部分。对此不屑一顾是不让您的问题得到回答的好方法(如果我在回答之前看到了您的评论,我就不会花时间来帮助您。)
  • 我在这里问了很多问题,这是我第一次因为意外的语法错误而被否决。你回答了,它奏效了,对我来说已经足够好了。
  • 我在这里回答了很多问题,这是我第一次让提问者如此粗鲁。

标签: javascript jquery animation comma


【解决方案1】:

只需在您当前设置元素text() 的任何位置添加逗号。

add commas to a number in jQuery 提取的逗号代码

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({
    countNum: $this.text()
  }).animate({
      countNum: countTo
    },

    {
      duration: 5000,
      easing: 'linear',
      step: function() {
        $this.text(commaSeparateNumber(Math.floor(this.countNum)));
      },
      complete: function() {
        $this.text(commaSeparateNumber(this.countNum));
        //alert('finished');
      }
    }
  );

});

function commaSeparateNumber(val) {
  while (/(\d+)(\d{3})/.test(val.toString())) {
    val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
  }
  return val;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="counter" data-count="1000000"></span>

【讨论】:

  • 这段代码比很多github专柜项目好用,而且非常轻量级。谢谢!
【解决方案2】:

如果字符串包含逗号,请使用parseFloat。 请检查以下工作代码

$('.counter').each(function() {
    $(this).prop('Counter', 0).animate({
        Counter: parseFloat($(this).text().replace(/,/g, ''))
    }, {
        duration: 10000,
        easing: 'swing',
        step: function(now) {
            $(this).text(getRupeesFormat(Math.ceil(now)));
        }
    });
});


function getRupeesFormat(val) {
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
    }
    return val;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    相关资源
    最近更新 更多