使用像$这样的函数的普通增量数字.用逗号动画

plain increment number using function like $.animate with comma

本文关键字:数字 动画 函数      更新时间:2023-09-26

我正在开发一款游戏,它将使增加或减少的钱动画化。

jquery解决方案在这里:

如何使用jQuery与逗号使用动画增加数字?

我如何在纯javascript中做到这一点?

我想避免使用jquery

在这个解决方案中,不需要jQuery

var from=40000, to=50000;
function increment() {
    setTimeout(function() {
        from++;
        if(from <= to) {
            document.getElementById("test").innerHTML = from;
            increment();
        }
    }, 10);
}
increment();

请访问网站。http://jsfiddle.net/TTaA4/

    var counter = 0;
    var timer = setInterval(function () {
        if (counter >= 100 ) {
            clearInterval(timer);
        }
        counter++;
        // call numberWithCommas(counter) to get no.s with comma..
    }, 100);
function numberWithCommas(x) {
    return x.toString().replace(/'B(?=('d{3})+(?!'d))/g, ",");
}

上面逗号函数的代码是无耻地从https://stackoverflow.com/a/2901298/2466168

http://jsfiddle.net/2MwSv/

在你的javascript控制台中试试:

var a = 40000;
var b = 45000;
console.log(commaSeparateNumber(a));
function animate(opts) {
    var start = new Date;
    var id = setInterval(function () {
        var timePassed = new Date - start
        var progress = timePassed / opts.duration
        if (progress > 1) progress = 1
        var delta = progress;
        opts.step(delta)
        if (progress == 1) {
            clearInterval(id)
        }
    }, opts.delay || 10)
}
function commaSeparateNumber(val) {
    while (/('d+)('d{3})/.test(val.toString())) {
        val = val.toString().replace(/('d)(?=('d'd'd)+(?!'d))/g, "$1,");
    }
    return val;
}

animate({
    delay: 10,
    duration: 3000,
    step: function (progress) {
        var difference = b - a;
        console.log(commaSeparateNumber(a + Math.round(progress * difference)));
    }
});

来源:http://javascript.info/tutorial/animation

如何使用jQuery与逗号使用动画增加数字?