动画数字计数器不显示十进制数字

时间:2018-06-04 10:15:42

标签: javascript jquery

早上好,

我有一个动画号码计数器,从0到指定的数字计数。但是,如果我输入一个十进制数字(即99.99%),它会向上舍入到100%。有没有办法让它计算到给出的数字?

如果您需要更多信息,请与我们联系。

提前致谢!



numbersAnimate(_Panel) {

    if (!_Panel) {
      return;
    }

    // Get document language
    const _Document = document.documentElement;
    let lang = _Document.getAttribute('lang');

    // Grab all panel amount nodes
    const _PanelAmounts = _Panel.querySelectorAll('.panel__amount');
    if (!_PanelAmounts) {
      return;
    }

    //Loop over all the panel amounts
    for (const _PanelAmount of _PanelAmounts) {

      //Convert to jQuery object
      const $PanelAmount = $(_PanelAmount);

      //Panel amount stored in value
      const value = $PanelAmount.data('amount');

      //If there is no value return
      if (!value || value.length < 1) {
        return;
      }

      // If not a number return
      if (isNaN(value)) {
        return;
      }

      //Animation....
      $PanelAmount.prop('Counter', 0).animate({
        Counter: value
      }, {
        duration: 1000,
        easing: 'linear',
        step: function(now) {
          $PanelAmount.text(this.Counter.toFixed());
        }
      });

    }

    //Add animated class because scroll event checks if it's there, if it isn't then add it.
    _Panel.classList.add('animated');





    //JSON Structure

    "statistic": {
      "amount": "99.99",
      "symbol": "%"
    },
&#13;
<span className="panel__amount panel-text-style-c" data-amount={jsonData.statistic.amount}>0</span>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您正在使用Math.ceil(now),它将舍入到最接近的整数。你试过删除吗?

$PanelAmount.text(now).toLocaleString(lang);

答案 1 :(得分:0)

旧:

//Panel amount is the animated number

$PanelAmount.prop('Counter', 0).animate({
  Counter: value
}, {
  duration: 1000,
  easing: 'linear',
  step: function(now) {
    $PanelAmount.text(Math.ceil(now)).toLocaleString(lang);
  }
});

新:

&#13;
&#13;
function startCounter(){
	$('.PanelAmount').each(function (index) {
        var size = $(this).text().split(".")[1] ? $(this).text().split(".")[1].length : 0;
	    $(this).prop('Counter',0).animate({
	        Counter: $(this).text()
	    }, {
	        duration: 2000,
	        easing: 'swing',
	        step: function (now) {
	            $(this).text(parseFloat(now).toFixed(size));
	        }
	    });
	});
}	

startCounter();
&#13;
.PanelAmount {
  
    font-size: 30px;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="counter">99.99</div>
&#13;
&#13;
&#13;

New JQuery工作到精确的小数点