我正在工作的网站上有一个工作号码计数器部分,我对JS不太了解,我有一些有效的代码,但它破坏了前端并停止了计数器。我希望有人能帮助我理解如何正确地整理我的作品。
我已经分别或同时尝试了两个功能,可能不正确。第二个函数处理千位逗号,但是它取消了前端和计数功能。
我不确定#shiva元素会发生什么,但是我已经将其整体替换为#counter,因为该功能可以全面使用,而不仅仅是一个div元素。如果有其他方法,我刚才已经将两者都留了。
HTML:
<div id="counter">
<div class="row">
<div class="col span-1-of-2">
<div class="row">
<div id="shiva"><span class="count">1688019</span></div>
<h2>Text</h2>
</div>
<div class="row">
<div id="shiva"><span class="count">82150</span></div>
<h2>Text</h2>
</div>
</div>
<div class="col span-1-of-2">
<div class="row">
<div id="shiva"><span class="count">10505</span></div>
<h2>Text</h2>
</div>
<div class="row">
<div id="shiva"><span class="count">168260</span></div>
<h2>Text</h2>
</div>
</div>
</div>
</div>
计数器:
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 2000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
分隔符:
function numberWithCommas(number) {
var parts = number.toString().split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return parts.join('.');
}
$('#counter').each(function () {
var num = $(this).text();
var commaNum = numberWithCommas(num);
$(this).text(commaNum);
});
答案 0 :(得分:1)
有人用类似的例子回答了成千上万的逗号,您只需要适应您的情况即可。在此处阅读How to print a number with commas as thousands separators in JavaScript
动画制作后需要更换的计数器,
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 2000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
$(this).text(convert($(this).text()))
}
});
});
步骤:
示例
const convert = str => {
// Find the number
let regx = /(\d{1,3})(\d{3}(?:,|$))/;
// Set a variable
let currStr;
// Start loop
do {
// Replace current string, split it
currStr = (currStr || str.split(`.`)[0])
.replace(regx, `$1,$2`)
} while (currStr.match(regx)); // Loop
// Return our result from function
return (str.split(`.`)[1]) ?
currStr.concat(`.`, str.split(`.`)[1]) :
currStr;
};
function total() {
let total = 0;
$('.count').each(function() {
let v = parseInt($(this).text());
total = v + total
})
return total;
}
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 2000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
$(this).text(convert($(this).text()))
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">
<div class="row">
<div class="col span-1-of-2">
<div class="row">
<div id="shiva"><span class="count">1688019</span></div>
<h2>Text</h2>
</div>
<div class="row">
<div id="shiva"><span class="count">82150</span></div>
<h2>Text</h2>
</div>
</div>
<div class="col span-1-of-2">
<div class="row">
<div id="shiva"><span class="count">10505</span></div>
<h2>Text</h2>
</div>
<div class="row">
<div id="shiva"><span class="count">168260</span></div>
<h2>Text</h2>
</div>
</div>
</div>
</div>