我的网站上的动画计数器遇到问题。该计数器旨在模拟统计数据,并且在桌面浏览器上完美运行。然而,当在生产环境中的移动设备上访问时,解析或转换似乎存在问题,会重置 999 以上的任何数字,从而重置初始数字。
以下是相关的 HTML 代码片段:
<span id="counter">4898988</span><br />
以下是相关的 JavaScript 代码片段:
document.addEventListener('DOMContentLoaded', (event) => {
const counterElement = document.getElementById('counter');
console.log('counterElement:', counterElement); // log the counterElement
counterElement.textContent = `${parseInt(counterElement.textContent, 10).toLocaleString()} USD`; // format the initial number
console.log('counterElement.textContent after formatting:', counterElement.textContent); // log the textContent after formatting
animateCount(counterElement);
// Animate the counter
function animateCount(targetElement) {
console.log('targetElement in animateCount:', targetElement); // log the targetElement in animateCount
let count = parseInt(targetElement.textContent.replace(/,/g, ''), 10);
console.log('count after parsing:', count); // log the count after parsing
const finalCount = count + Math.floor(Math.random() * 31); // generate a random number between 0 and 30
const interval = setInterval(() => {
if (count < finalCount) {
count++;
targetElement.textContent = `${count.toLocaleString()} USD`;
} else {
clearInterval(interval);
setTimeout(() => animateCount(targetElement), Math.random() * 9000 + 5000); // wait for a random period between 5 and 14 seconds before starting the next cycle
}
}, 100);
}
});
控制台日志:
[Log] counterElement:
<span id="counter">4 898 988 USD</span>
[Log] after formatting: – "4 898 988 USD"
[Log] animateCount:
<span id="counter">4 898 988 USD</span>
[Log] count after parsing: – 4
如您所见,“let count =”行似乎无法正确解析 999 以上的数字。
toLocaleString
的行为会根据用户的本地情况而变化,这使得解析它比应有的复杂得多。
一个解决方案是跟踪变量中的计数,而不是每次都从 DOM 解析它:
工作示例:https://codepen.io/jacob_124/pen/JjVbjoL
document.addEventListener("DOMContentLoaded", (event) => {
const counterElement = document.getElementById("counter");
// Initialize number based off of text
const num = parseInt(counterElement.textContent, 10);
counterElement.textContent = `${num.toLocaleString()} USD`; // format the initial number
console.log(
"counterElement.textContent after formatting:",
counterElement.textContent
); // log the textContent after formatting
animateCount(counterElement, num);
// Animate the counter
function animateCount(targetElement, count) {
const finalCount = count + Math.floor(Math.random() * 31); // generate a random number between 0 and 30
const interval = setInterval(() => {
if (count < finalCount) {
count++;
targetElement.textContent = `${count.toLocaleString()} USD`;
} else {
clearInterval(interval);
setTimeout(
() => animateCount(targetElement),
Math.random() * 9000 + 5000
); // wait for a random period between 5 and 14 seconds before starting the next cycle
}
}, 100);
}
});