我需要一些与您想要的非常相似的东西,除了我需要能够为美元和美分的变化设置动画(类似于 Turbotax 计数器)。我在网上找不到任何有用的东西,所以我从 SO 上的几个示例中一起破解了这个。关键是使用 step 回调函数随意格式化值。很酷的是,无论您的价值是上升还是下降,这都有效。
希望此代码对您有所帮助。
<div id="total">$9.99</div>
<script>
//NOTE: Always work with currency in total value in cents,
//hence the need for .toMoney() and .fromMoney()
var $total = jQuery("#total");
var finaltotal = 29999; //$299.99
var currval = $total.text().fromMoney();
//only animate if the values are different
if(currval !== finaltotal) {
console.log("start: " + currval);
console.log("end: " + finaltotal);
$({"counter": currval })
.animate({ counter: finaltotal },
{
duration: 500,
easing: "swing",
step: function() {
$total.text( this.counter.toMoney() );
},
complete: function() {
//animate is a bit off more often than not.
//Nobody will notice if the animation happens quickly
//so after the animate is done we slam in the final value.
$total.text( finaltotal.toMoney() );
console.log("animate complete");
}
});
}
//Convert a currency string (with or without dollar sign or commas)
//to an integer representing total value in cents
//E.g.: $149.99 becomes 14999
String.prototype.fromMoney = function() {
return parseInt(this.replace(/^\$/,'').replace(/,/g, '').replace(/\./, ''));
}
//Convert a given integer representing only cents ($149.99 = 14999) to a
//proper, comma delimited US dollar amount with the dollar sign
//Modern browsers from IE 11 onward support
//foo.toLocaleString("en-US", {style:"currency", currency:"USD"});
//but the method below works for most older browsers.
//Found on SO @ http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
Number.prototype.toMoney = function(c, d, t) {
var n = this/100,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+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>