首頁  >  問答  >  主體

動畫數位計數器中的逗號放置

我一直在嘗試 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粉277824378P粉277824378277 天前519

全部回覆(1)我來回復

  • P粉211273535

    P粉2112735352024-01-17 00:50:16

    閱讀 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());
          }
        });
      }
    }

    回覆
    0
  • 取消回覆