Jquery算上动画? [英] Jquery Count up Animation?
问题描述
我有一个计数器,需要在x秒内(最可能是3秒)从$ 0到$ 10,000计数。
I have a a counter that needs to count up from $0 to $10,000 in x seconds (most likely 3 seconds).
只是直接的文字,有点像毫秒倒数计时器,但向上并带有美元符号。
Just straight text, kind of like a millisecond countdown timer, but upwards and with a dollar sign.
我宁愿不使用庞大的插件,因为这只需要在x秒内循环1-10,00并且每100毫秒更新一次。
I'd rather not use a bulky plugin as this just needs to loop through 1-10,00 in x seconds and update every 100ms or so.
我坚持创建将要更新的循环,我应该从哪里开始?
I'm stuck at creating the loop that will update, where should I start?
以下是我到目前为止点击事件的内容:
Here is what I've got so far on a click event:
function countUp() {
console.log('counted');
}
setInterval("countUp()", 1000)
推荐答案
我会使用 http:// www .mredkj.com / javascript / numberFormat.html 添加逗号:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
然后我使用setInterval来计算最多1000个,如下所示:
I'd then use setInterval to count up to 1000, something like this:
var x = 1;
var interval = setInterval(
function(){
if (x < 10000){
x = parseInt(x) + 100;
if(x > 10000){x = 10000}
$('#number').html("$" + addCommas(x));
}},
10);
诀窍是让它在3秒内发生,因为javascript的执行速度因浏览器而异。在FireFox和谷歌浏览器中,10毫秒的延迟和100次跳跃计数。
The trick is to get it to happen in 3 seconds since the execution speed of javascript varies between browsers. The 10 millisecond delay and counting in jumps of 100 worked for me in FireFox and Google Chrome.
上面的代码将每10毫秒继续运行,但实际上不会改变任何超过10,000美元的东西。因此,只要将x设置为小于10,000的值,它就会再次开始计数。但是,您可以使用 clearInterval(interval)
The code above will keep running every 10 milliseconds, but won't actually change anything once it exceeds $10,000. It can therefore will start counting up again as soon as you set x to something less than 10,000. However you can stop executing the code by using clearInterval(interval)
这篇关于Jquery算上动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!