【问题标题】:Money Count Up with Javascript using Date()使用 Javascript 使用 Date() 进行金钱计数
【发布时间】:2017-04-30 06:24:07
【问题描述】:

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

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

以下是我想要调整的 Count Up 功能示例。虽然我不会像他们在示例中那样使用“数据计数”属性。

$('.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, "$1" + 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>

如有任何帮助,我们将不胜感激。

【问题讨论】:

    标签: javascript jquery counter


    【解决方案1】:

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

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

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

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

    jsFiddle

    【讨论】:

    • 你这么多的详细解释 Sasang。这是完美的!
    猜你喜欢
    • 2011-12-12
    • 2011-04-17
    • 2011-10-19
    • 1970-01-01
    • 2011-11-02
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多