我有一个带有开始日期但没有结束日期的计数器。基本上,开始日期后每一秒都会增加 41.70 美元/秒。这会无限期地持续下去。
我已经构建了该功能。我唯一遇到的困难是我希望它像自动收报机一样从美分开始计数。 (例如 1,200.98 -> 1,200.99 -> 1,201.00 等)
这是我想要采用的“向上计数”功能的示例。虽然我不会像示例中那样使用“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, "$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>
任何解决这个问题的帮助都将不胜感激。
最佳答案
我能够从你的例子中得到一个滚动计数器。关键是将金额的当前值和预期值传递到 animateCount 函数中。然后在这个函数中,在 perSecond
元素上调用 animate
之前,首先给它一个自定义属性,我将其命名为 counter
,并设置其值更改为当前金额值。然后在 animate 函数中,您告诉它在定义的持续时间内将此属性更新为预期的下一个值。
提供动画的持续时间和类型后,您可以定义 step
函数(如您提供的示例中所示)。动画的每个步骤都会调用此方法,因此非常适合以滚动方式更新文本。在此函数中,您设置元素的文本值,该值只是使用 formatMoney
函数格式化的计数器属性。
现在您所要做的就是每次调用 startDate
时调用此动画函数。请注意,您不要直接在此处设置 perSecond
的文本值,animate 函数会处理它。此外,动画的持续时间和超时的长度应该是相同的值,以使其具有无缝计数器。
我已经向 jsfiddle 添加了一个工作代码,请看一下:
<强> jsFiddle
关于javascript - 使用 Date() 通过 Javascript 进行金钱计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43703583/