JS计数器不断更新 [英] JS counter continuously updating

查看:82
本文介绍了JS计数器不断更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实施现场直播和网站上的永久数字计数器

所以我一直在看这个问题(^),我想做的是完全一样的事情,只是有所不同。

So I was looking at this question (^) and I want to do the exact same thing except a little different.

我需要其中之一,它从麻木的$ 138,276,343中每秒计数15.8美分

I need one of these that counts up 15.8 cents per second from the numb $138,276,343

我希望像普通的美元金额一样有逗号。

Preferably I would like to have the commas like a normal dollar amount.

任何方式都可以使它正常工作吗?我很沮丧像上述问题的发布者一样,我对JS的了解也不多。

Any way I could get this working? I'm stumped. Like the poster of the above question, I don't have much JS knowledge.

推荐答案

这花了我很长时间答案,因为我必须创建自己的格式货币函数。

This took me quite a long time to answer since I had to create my own format currency function.

可以在此处找到实时演示:http://jsfiddle.net/dm6LL/

A live demo can be found here: http://jsfiddle.net/dm6LL/

每秒的基本更新非常容易,并且可以完成通过JavaScript的 setInterval 命令。

The basic updating each second is very easy and will be done through JavaScript's setInterval command.

setInterval(function(){
    current += .158;
    update();
},1000);

您在 update()函数中看到的上面的代码只是一个简单的更新程序,引用具有 amount id的对象将格式化后的当前金额放入页面上的div中。

The update() function you see in the above code is just a simple updater referencing an object with the amount id to put the formatted current amount into a div on the page.

function update() {
    amount.innerText = formatMoney(current);
}

update( )函数是预定义的:

var amount = document.getElementById('amount');
var current = 138276343;

然后剩下的就是我的 formatMoney()

Then all that's left is my formatMoney() function which takes a number and converts it into a currency string.

function formatMoney(amount) {
    var dollars = Math.floor(amount).toString().split('');
    var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
    if(typeof cents == 'undefined'){
        cents = '00';
    }else if(cents.length == 1){
        cents = cents + '0';
    }
    var str = '';
    for(i=dollars.length-1; i>=0; i--){
        str += dollars.splice(0,1);
        if(i%3 == 0 && i != 0) str += ',';
    }
    return '$' + str + '.' + cents;
}​

这篇关于JS计数器不断更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆