我已经尝试了我在网上可以找到的所有内容,但它们似乎都处理静态数字,而不是动画数字。
是否可以通过修改此函数将逗号添加到我的值中,因为数字会增加?
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 500,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
答案 0 :(得分:4)
只需在当前设置元素text()
的任何位置添加逗号。
逗号代码取自add commas to a number in jQuery
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 5000,
easing: 'linear',
step: function() {
$this.text(commaSeparateNumber(Math.floor(this.countNum)));
},
complete: function() {
$this.text(commaSeparateNumber(this.countNum));
//alert('finished');
}
}
);
});
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return val;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="counter" data-count="1000000"></span>
答案 1 :(得分:4)
如果字符串包含逗号,请使用parseFloat
。
请检查以下工作代码
$('.counter').each(function() {
$(this).prop('Counter', 0).animate({
Counter: parseFloat($(this).text().replace(/,/g, ''))
}, {
duration: 10000,
easing: 'swing',
step: function(now) {
$(this).text(getRupeesFormat(Math.ceil(now)));
}
});
});
function getRupeesFormat(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return val;
}