动画数字计数器中的逗号放置
P粉277824378
P粉277824378 2024-01-16 14:43:34
0
1
516

我一直在尝试 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>

P粉277824378
P粉277824378

全部回复(1)
P粉211273535

阅读 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());
      }
    });
  }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!