我有3个数字(90,75.5,2.5)。我在jquery中使用一个计数器,递增1这个数字。我想只增加1而不是递增小数。结果必须是(90,75.5,2.5)而不是(90.0,75.5,2.5)是否可能?
$(".count").delay(2000).each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 2500,
easing: 'swing',
step: function(now) {
$(this).text(now);
},
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="count">90</div>
<div class="count">75.5</div>
<div class="count">2.5</div>
动画计数器值将遵循您应用于动画的任何缓动函数,但您可以在step
函数中操纵该值的显示。
在这里我捕捉动画开始前的数字的小数部分;并在动画的每一步圆形计数器,然后替换原来的小数部分:
$(".count").delay(2000).each(function() {
// capture the original decimal.
// This would be nice, but doesn't work for negative numbers and is prone to floating point errors:
// var mantissa = Number($(this).text()) - Math.floor($(this).text());
// so instead we'll use icky string manipulation:
var mantissa = 0;
var orig = $(this).text();
if (orig.indexOf('.')>-1) {
mantissa = orig.substring(orig.indexOf('.'))
}
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 2500,
easing: 'swing',
step: function(now) {
$(this).text(Math.floor(now) + mantissa);
},
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="count">90</div>
<div class="count">75.5</div>
<div class="count">2.5</div>
<div class="count">-1000.15</div><!-- confirming this works for negative numbers too -->