jQuery 计数器在动画后无法显示正确的值



我有一个jQuery计数器,每次检查单选按钮时都会更新,将其值添加到等式中。目前为止,一切都好。但是,一旦选中具有高值的单选按钮,计数器动画就无法显示正确的数字。例如,它将显示 999 998 而不是 1 000 000,依此类推。下面是脚本:

$(window).load(function(){
$('input[type="radio"]').change(function () {
var total_span = 0;
$('input[type="radio"]').each(function () {
total_span += this.checked && +this.value; 
});
$({counter: +$('#total').text()}).animate({counter: total_span},{
duration: 1000,
easing: 'swing',
step: function () {
$('#total').text(Math.floor(this.counter));
$('#total-2').text(Math.floor(this.counter));
}
}); 
});   
}); 

你们中有解决这个问题的方法吗?如果有人能帮助我:),将不胜感激

编辑:您可以在此处看到问题: http://moodboy.se/radiobuttons/

jQuery animate 函数旨在处理 css 动画。它通过使用计时器在两个元素之间">补间">来工作。结果会根据补间的大小而有所不同。

这种精度的缺乏意味着,在使用数字时,无法保证准确性。一种解决方案是使用动画函数的complete回调属性在完成时应用正确的值。

.animate( properties [, duration ] [, easing ] [, complete ] )

$(window).load(function(){
$('input[type="radio"]').change(function () {
var total_span = 0;
$('input[type="radio"]').each(function () {
total_span += this.checked && +this.value; 
});
$({counter: + $('#total').text()}).animate({counter: total_span},{
duration: 1000,
easing: 'swing',
step: function () {
$('#total').text(Math.floor(this.counter));
$('#total-2').text(Math.floor(this.counter));
},
complete : function(){
$('#total').text(total_span);
}
}); 
});   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="togglelinks">
<ul>
<li><a class="toggle" href="#panel-one">Choices 1</a></li>
<li><a class="toggle" href="#panel-two">Choices 2</a></li>
<li><a class="toggle" href="#show-all" id="demo">Results</a></li>
</ul>
<span id="total">974996</span>
<div class="clear"></div>
</div>
<div id="panel-one" class="info-panel">
<h1>Choices 1</h1>
<label><input id="1001" name="choices-1" value="1195000" type="radio">1195000</label>
<label><input id="1002" name="choices-1" value="925000" type="radio">925000</label>
<label><input id="1003" name="choices-1" value="1275000" type="radio">1275000</label>
<label><input id="1004" name="choices-1" value="1195000" type="radio">1195000</label>
<label><input id="1005" name="choices-1" value="1195000" type="radio">1195000</label>
<label><input id="1006" name="choices-1" value="1295000" type="radio">1295000</label>
<p>
<label><input id="2001" name="choices-1" value="1250000" type="radio">1250000</label>
<label><input id="2002" name="choices-1" value="975000" type="radio">975000</label>
<label><input id="2003" name="choices-1" value="1295000" type="radio">1295000</label>
<label><input id="2004" name="choices-1" value="1250000" type="radio">1250000</label>
<label><input id="2005" name="choices-1" value="1250000" type="radio">1250000</label>
<label><input id="2006" name="choices-1" value="1345000" type="radio">1345000</label>
</p>
<a class="toggle" href="#panel-two">&gt; Choices 2</a>
</div>

最新更新