【问题标题】:Animating counter from zero with commas用逗号从零开始动画计数器
【发布时间】:2015-12-30 13:51:11
【问题描述】:

我已经能够使用 this code 为从零开始的数字设置动画:

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

但是我需要用逗号显示我的号码,例如30,000,000。当我这样做时,此代码将失败。有没有一种简单的方法让它适用于这种格式?

【问题讨论】:

标签: jquery date animation counter


【解决方案1】:

你可以添加

.toLocaleString('en')

到step属性:

step: function(now) {
    $(this).text(Math.ceil(now).toLocaleString('en'));
}

您也可以传入 navigator.language 而不是 'en',小数点将根据用户浏览器语言设置显示。

【讨论】:

    【解决方案2】:
    $('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
    now = Number(Math.ceil(now)).toLocaleString('en');
            $(this).text(now);
        }
       });
    });
    

    【讨论】:

      【解决方案3】:

      可以使用正则表达式替换来完成:

      $(function(){
      
        $('.count').each(function () {
          $(this).prop('Counter',0).animate({
              Counter: $(this).text()
          }, {
              duration: 4000,
              easing: 'swing',
              step: function (now) {
                  $(this).text(Math.ceil(now).toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
              }
          });
        });
        
      });
      #shiva
      {
        width: 100px;
      	height: 100px;
      	background: red;
      	-moz-border-radius: 50px;
      	-webkit-border-radius: 50px;
      	border-radius: 50px;
        float:left;
        margin:5px;
      }
      .count
      {
        line-height: 100px;
        color:white;
        margin-left:30px;
        font-size:25px;
      }
      #talkbubble {
         width: 120px;
         height: 80px;
         background: red;
         position: relative;
         -moz-border-radius:    10px;
         -webkit-border-radius: 10px;
         border-radius:         10px;
        float:left;
        margin:20px;
      }
      #talkbubble:before {
         content:"";
         position: absolute;
         right: 100%;
         top: 26px;
         width: 0;
         height: 0;
         border-top: 13px solid transparent;
         border-right: 26px solid red;
         border-bottom: 13px solid transparent;
      }
      
      .linker
      {
        font-size : 20px;
        font-color: black;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="shiva"><span class="count">200</span></div>
      <div id="shiva"><span class="count">10000</span></div>
      <div id="shiva"><span class="count">8530</span></div>
      <div id="shiva"><span class="count">1540</span></div>
      <div id="shiva"><span class="count">10</span></div>
      <div id="shiva"><span class="count">87</span></div>
      <div style="clear:both"></div>
      <div id="talkbubble"><span class="count">1421</span></div>
      <div id="talkbubble"><span class="count">145</span></div>
      <div id="talkbubble"><span class="count">78</span></div>
      <br />
      <br />
      <a class="linker" href="http://www.i-visionblog.com/2014/11/jquery-animated-number-counter-from-zero-to-value-jquery-animation.html"  target="_blank">visit Tutorial in Blog</a>
      <br />

      【讨论】:

        【解决方案4】:

        我需要一些与您想要的非常相似的东西,除了我需要能够为美元和美分的变化设置动画(类似于 Turbotax 计数器)。我在网上找不到任何有用的东西,所以我从 SO 上的几个示例中一起破解了这个。关键是使用 step 回调函数随意格式化值。很酷的是,无论您的价值是上升还是下降,这都有效。

        希望此代码对您有所帮助。

        <div id="total">$9.99</div>
        
        <script>
        
        //NOTE: Always work with currency in total value in cents, 
        //hence the need for .toMoney() and .fromMoney()
        
        var $total     = jQuery("#total");
        var finaltotal = 29999; //$299.99
        var currval    = $total.text().fromMoney(); 
        
        //only animate if the values are different
        if(currval !== finaltotal) {
        
            console.log("start: " + currval);
            console.log("end:   " + finaltotal);
        
            $({"counter": currval })
                .animate({ counter: finaltotal },
                    { 
                        duration: 500,
                        easing: "swing",
                        step: function() { 
                            $total.text( this.counter.toMoney() ); 
                        },
                        complete: function() {
        
                            //animate is a bit off more often than not.
                            //Nobody will notice if the animation happens quickly
                            //so after the animate is done we slam in the final value.
        
                            $total.text( finaltotal.toMoney() );
                            console.log("animate complete");
                        }
                    });
        }
        
        
        //Convert a currency string (with or without dollar sign or commas) 
        //to an integer representing total value in cents
        //E.g.: $149.99 becomes 14999
        String.prototype.fromMoney = function() {
            return parseInt(this.replace(/^\$/,'').replace(/,/g, '').replace(/\./, ''));
        }
        
        //Convert a given integer representing only cents ($149.99 = 14999) to a
        //proper, comma delimited US dollar amount with the dollar sign
        //Modern browsers from IE 11 onward support 
        //foo.toLocaleString("en-US", {style:"currency", currency:"USD"});
        //but the method below works for most older browsers.
        //Found on SO @ http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
        Number.prototype.toMoney = function(c, d, t) {
        var n = this/100, 
            c = isNaN(c = Math.abs(c)) ? 2 : c, 
            d = d == undefined ? "." : d, 
            t = t == undefined ? "," : t, 
            s = n < 0 ? "-" : "", 
            i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
            j = (j = i.length) > 3 ? j % 3 : 0;
        
            return s + "$" + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3}) (?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
        }
        
        </script>
        

        【讨论】:

          【解决方案5】:

          您可以像这样在步进动画结束时格式化整个字符串:

          $('.count').each(function () {
                  var obj = $(this);
                  jQuery({Counter: 0}).animate({Counter: obj.attr('data-stop')}, {
                      duration: 1000,
                      easing: 'swing',
                      step: function (now) {
                          obj.text(Math.ceil(now));
                      },
                      complete : function(){
                          obj.text(Math.ceil(obj.text()).toLocaleString('en'));
                      }
                  })
              });
          

          (我使用了 Shankar 的脚本jQuery Count Numbers Up

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-11-12
            • 2022-08-17
            • 2022-12-25
            • 1970-01-01
            • 2014-07-27
            • 1970-01-01
            相关资源
            最近更新 更多