我正在开发一款能够为增加或减少的钱设置动画的游戏。
jquery解决方案在这里:
How to increment number using animate with comma using jQuery?
如何在普通的javascript中执行此操作?
我想避免使用jquery
答案 0 :(得分:1)
在此解决方案中,不需要jQuery
var from=40000, to=50000;
function increment() {
setTimeout(function() {
from++;
if(from <= to) {
document.getElementById("test").innerHTML = from;
increment();
}
}, 10);
}
increment();
请访问jsfiddle。 http://jsfiddle.net/TTaA4/
答案 1 :(得分:0)
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
无耻地复制的答案 2 :(得分:0)
在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
How to increment number using animate with comma using jQuery?