繁体   English   中英

带小数位的 Javascript 计数器

[英]Javascript counter with decimal places

这里有一个 jsfiddle

这是一个简单的 javascript 函数,可以计数到一个设定的数字。

是否可以进行此计数,但也可以保留一位小数

所以它计数为 1.1、1.2、1.3 等。

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

    startCounter();

更新

使用 .split() 检查尾数的大小。

var size = $(this).text().split(".")[1] ? $(this).text().split(".")[1].length : 0;

然后用它来估计像这样的 .toFixed() 大小

$(this).text(parseFloat(now).toFixed(size));

这是一个更新的演示https://jsfiddle.net/dhirajbodicherla/wmaftobx/13/


而不是 Math.ceil Math.ceil(now)使用.toFixed(1)像这样

parseFloat(now).toFixed(1)

这是更新的演示https://jsfiddle.net/wmaftobx/6/

这就是我所做的:用 $(this) $(this).text(Math.ceil(now)/10)Counter: $(this).text()替换$(this).text(Math.ceil(now)) Counter: $(this).text()*10 它将增加十分之一。 每增加一个小数位,除以或乘以 10。

换一行。。

$(this).text(Math.ceil(now));

$(this).text(Math.round( now * 10 ) / 10);

这是更新代码的小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM