jQuery Counter,动画一共,但我如何包含逗号?
Posted
技术标签:
【中文标题】jQuery Counter,动画一共,但我如何包含逗号?【英文标题】:jQuery Counter, animating to a total, but how do I include a comma? 【发布时间】:2012-10-30 00:07:32 【问题描述】:我在这里找到了许多计数器的解决方案,从一个总数到另一个动画。
这是我现在正在使用的:
jQuery.fn.extend(
ts : function (from, to, time)
var steps = 1,
self = this,
counter;
if (from - to > 0)
steps = -1;
;
from -= steps;
function step()
self.text(from += steps);
if ((steps < 0 && to >= from) || (steps > 0 && from >= to))
clearInterval(counter);
;
;
counter = setInterval(step, time || 5);
);
var total = $('.total').ts(56000,56941);
效果很好,但是我想在总数中添加一个逗号,例如 56,941。这可能吗?
谢谢!
【问题讨论】:
【参考方案1】:我想这会做到:
jQuery.fn.extend(
ts: function(from, to, time)
var steps = 1, self = this, counter;
if (from - to > 0) steps = -1;
from -= steps;
function step()
var x = (from += steps).toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
self.text(x);
if ((steps < 0 && to >= from) || (steps > 0 && from >= to))
clearInterval(counter);
;
;
counter = setInterval(step, time || 5);
);
FIDDLE
【讨论】:
【参考方案2】:来自网络上的某个地方...
function formatComma(x)
return (x+'').replace( /\B(?=(\d3)+(?!\d))/g, ',');
我更喜欢我自己的反转字符串的解决方案,因为它更容易理解逻辑......
function formatComma(x)
// prepare the input as a string ready for manipulating and returning
return (x+'')
// reverse the string (by converting to array)
.split("").reverse().join("")
// replace 3 digits in a row, with themselves and a comma
// so long as the digits are followed by a non-word boundary
.replace(/(\d3)\B/g,'$1,')
// reverse it all again
.split("").reverse().join("")
【讨论】:
请将您找到的代码归于(至少)您找到它的地方或作者! 不,我不久前找到了它,并将它保存为一个 sn-p - 不知道我从哪里得到它,尽管我很有可能在堆栈溢出时在这里找到它。【参考方案3】:这会奏效。该函数取自http://ntt.cc/2008/04/25/6-very-basic-but-very-useful-javascript-number-format-functions-for-web-developers.html。很方便
jQuery.fn.extend(
ts : function (from, to, time)
var steps = 1,
self = this,
counter;
if (from - to > 0)
steps = -1;
;
from -= steps;
function step()
self.text(addCommas(from += steps));
if ((steps < 0 && to >= from) || (steps > 0 && from >= to))
clearInterval(counter);
;
;
counter = setInterval(step, time || 5);
);
var total = $('.total').ts(56000,56941);
function addCommas(nStr)
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d3)/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + ',' + '$2');
return x1 + x2;
【讨论】:
【参考方案4】:没错!你可以检查这个插件 (http://code.google.com/p/jquery-numberformatter/) 并在你的插件中实现它:-)
【讨论】:
以上是关于jQuery Counter,动画一共,但我如何包含逗号?的主要内容,如果未能解决你的问题,请参考以下文章