我一直在尝试 HTML、CSS 和 JavaScript 的不同组合,这会给我一个滚动的动画数字计数器,每个数字旁边都有一个符号(+、% 等)。我终于找到了正确的组合;然而,它还不够完美。我想向 1,000 及以上的数字添加逗号,但是当我在 HTML 中添加逗号时,它会生成 NaN 输出。我对 JavaScript 非常陌生,我不知道在当前代码中添加或修复什么来显示逗号。
有人能够重写我当前的代码以显示逗号或指导我如何执行此操作吗?我将非常感谢任何帮助!
<script>
function inVisible(element) {
//Checking if the element is
//visible in the viewport
var WindowTop = $(window).scrollTop();
var WindowBottom = WindowTop + $(window).height();
var ElementTop = element.offset().top;
var ElementBottom = ElementTop + element.height();
//animating the element if it is
//visible in the viewport
if ((ElementBottom <= WindowBottom) && ElementTop >= WindowTop)
animate(element);
}
function animate(element) {
//Animating the element if not animated before
if (!element.hasClass('ms-animated')) {
var maxval = element.data('max');
var html = element.html();
element.addClass("ms-animated");
$({
countNum: element.html()
}).animate({
countNum: maxval
}, {
//duration 2 seconds
duration: 2000,
easing: 'linear',
step: function() {
element.html(Math.floor(this.countNum) + html);
},
complete: function() {
element.html(this.countNum + html);
}
});
}
}
//When the document is ready
$(function() {
//This is triggered when the
//user scrolls the page
$(window).scroll(function() {
//Checking if each items to animate are
//visible in the viewport
$("h2[data-max]").each(function() {
inVisible($(this));
});
})
});
</script> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
阅读 HTML 时删除逗号,显示时添加回来。
function animate(element) { //Animating the element if not animated before if (!element.hasClass('ms-animated')) { var maxval = element.data('max'); var html = element.html(); element.addClass("ms-animated"); $({ countNum: parseInt(element.html().replace(/,/g, '')) // remove commas }).animate({ countNum: maxval }, { //duration 2 seconds duration: 2000, easing: 'linear', step: function() { element.html((Math.floor(this.countNum) + html).toLocaleString()); }, complete: function() { element.html((Math.floor(this.countNum) + html).toLocaleString()); } }); } }