簡體   English   中英

jQuery:動畫十進制數字

[英]jQuery: animate decimal numbers

我正在嘗試為從0到36.6的數字設置動畫,但是目前還沒有運氣,因為它只是將最終值四舍五入為37,如您在此處的小提琴中所見: http : //jsfiddle.net/neal_fletcher/0f3hxej8/
必要的標記如下:

HTML

<div id="el"></div>

jQuery的:

// Animate the element's value from x to y:
  $({someValue: 0}).animate({someValue: 36.6}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $('#el').text(commaSeparateNumber(Math.round(this.someValue)));
      },
      complete:function(){
          $('#el').text(commaSeparateNumber(Math.round(this.someValue)));
      }
  });

 function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.");
    }
    return val;
  }

理想情況下,我希望它也可以通過小數點進行動畫處理,例如35.9、36.0、36.1、36.2等。任何建議將不勝感激!

您可以通過四舍五入到十進制小數位,然后四舍五入到十。

Math.round(this.someValue * 10) / 10)

如更新的jsfiddle中所示。

一種解決方案是使用MDN上提供的Math.round10函數。 您只需將代碼更改為:

 $('#el').text(commaSeparateNumber(Math.round10(this.someValue, -1)));

更新小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM