使用 Date() 以 Javascript 计算金钱

Money Count Up with Javascript using Date()

我有一个有开始日期但没有结束日期的计数器。基本上,开始日期之后的每一秒都会增加 41.70 美元/秒。这将无限期地持续下去。

我已经构建了功能。我唯一挣扎的部分是我希望它像从美分开始的自动收报机一样计数。 (例如 1,200.98 -> 1,200.99 -> 1,201.00 等)

下面是我想要调整的 Count Up 功能示例。虽然我不会像示例中那样使用 "data-count" 属性。

$('.counter').each(function() {
  var $this = $(this),
      countTo = $this.attr('data-count');
  
  $({ countNum: $this.text()}).animate({
    countNum: countTo
  },

  {

    duration: 8000,
    easing:'linear',
    step: function() {
      $this.text(Math.floor(this.countNum));
    },
    complete: function() {
      $this.text(this.countNum);
      //alert('finished');
    }

  });  
  
  

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter" data-count="2200">0</div>

这是我的代码:

window.onload = function() {
 startDate("May 01, 2017 00:00:00 EST");
};

function startDate(x) {
 rightNow = new Date();
 x = new Date(x);
 difference = rightNow - x;
 amtPerSecond = (41.70 * (difference / 1000)).formatMoney(2);
 $("#perSecond").text("$ " + amtPerSecond);
 clearTimeout(startDate.to);
 startDate.to = setTimeout(function() {
  startDate(x);
 }, 1000);
}


// Plug-in to combact safari's incompatibility with .toLocaleString() 
Number.prototype.formatMoney = function(c, d, t) {
 var n = this,
  c = isNaN((c = Math.abs(c))) ? 2 : c,
  d = d == undefined ? "." : d,
  t = t == undefined ? "," : t,
  s = n < 0 ? "-" : "",
  i = String(parseInt((n = Math.abs(Number(n) || 0).toFixed(c)))),
  j = (j = i.length) > 3 ? j % 3 : 0;
 return (
  s +
  (j ? i.substr(0, j) + t : "") +
  i.substr(j).replace(/(\d{3})(?=\d)/g, "" + t) +
  (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "")
 );
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="perSecond"></div>

如果能帮助解决这个问题,我们将不胜感激。

我能够从您的示例中获得一个滚动计数器。关键是将 amount 的当前值和期望值传递给一个 animateCount 函数。然后在这个函数中,在perSecond元素上调用animate之前,你先给它一个自定义的属性,我叫它counter,并将它的值设置为当前数量价值。然后在动画函数中,您告诉它在定义的持续时间内将此 属性 更新为预期的下一个值。

提供持续时间和动画类型后,您可以定义 step 函数(如您在提供的示例中所见)。动画的每一步都会调用它,因此非常适合以滚动方式更新文本。在此函数中,您设置元素的文本值,它只是使用 formatMoney 函数格式化的计数器 属性。

现在您所要做的就是在每次调用 startDate 时调用此动画函数。请注意,您不要直接在此处设置 perSecond 的文本值,动画函数会处理它。此外,动画的持续时间和超时的长度应该是相同的值,以使其具有无缝计数器。

我已经在 jsfiddle 中添加了一个工作代码,看看:

jsFiddle