这是我在我的页面上呈现自动增量计数器的代码:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var START_DATE_1 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
var INTERVAL_1 = 3; // in seconds
var INCREMENT_1 = 1; // increase per tick
var START_VALUE_1 = 0; // initial value when it's the start date
var count_1 = 0;
var msInterval_1 = INTERVAL_1 * 1000;
var now_1 = new Date();
count_1 = parseInt((now_1 - START_DATE_1)/msInterval_1) * INCREMENT_1 + START_VALUE_1;
document.getElementById('counter_1').innerHTML = count_1;
setInterval(function() {
count_1 += INCREMENT_1;
document.getElementById('counter_1').innerHTML = count_1;
}, msInterval_1);
});
</script>
我想用千位分隔符(例如:2.000.000)
渲染计数器的数字我该如何编辑脚本?
提前致谢。
答案 0 :(得分:1)
在现代浏览器上,您可以使用Intl API
Intl对象是ECMAScript的名称空间 Internationalization API,提供语言敏感字符串 比较,数字格式以及日期和时间格式。该 Collator,NumberFormat和DateTimeFormat对象的构造函数 是Intl对象的属性。本页记录了这些 属性以及国际化共有的功能 构造函数和其他语言敏感函数。
我在以下示例中使用意大利语,仅根据您的姓名使用您所需的格式。
var START_DATE_1 = new Date('July 18, 2016 10:30:00').getTime(); // put in the starting date here
var INTERVAL_1 = 3; // in seconds
var INCREMENT_1 = 1; // increase per tick
var START_VALUE_1 = 0; // initial value when it's the start date
var msInterval_1 = INTERVAL_1 * 1000;
var now_1 = Date.now();
var count_1 = Math.trunc((now_1 - START_DATE_1) / msInterval_1) * INCREMENT_1 + START_VALUE_1;
function formatNumber(number) {
return new Intl.NumberFormat('it').format(number);
}
document.getElementById('counter_1').textContent = formatNumber(count_1);
setInterval(function() {
count_1 += INCREMENT_1;
document.getElementById('counter_1').textContent = formatNumber(count_1);
}, msInterval_1);
&#13;
<pre id="counter_1"></pre>
&#13;