为什么jquery不能准确地为数字设置动画?

med*_*pir 8 html javascript jquery

我试图使用以下代码增加文本框中的数字

    // Animate the element's value from 0 to 1100000:
$({someValue: 0}).animate({someValue: 1100000}, {
    duration: 1000,
    step: function() { // called on every step
        // Update the element's text with value:
        $('#counterx').text(Math.floor(this.someValue+1));
    }
});
Run Code Online (Sandbox Code Playgroud)

它正在处理0到100之间的小数字,但是当涉及到如上述代码中的大数字时,它没有给出目标数字,它是动画到像1099933或1099610或.....这样的数字它改变.

那我怎么能让它动画到我指定的数字?

Ami*_*far 16

我有同样的问题.推理是因为animate函数使用基于时间的数学公式.在动画基于css的动画时你并没有真正注意到这一点,因为足够近的像素就足够了.它将接近最终值,但可能并不总是正确的最终值.解决方案是使用complete事件来设置最后一个值.

这是你需要做的:

function animateNumber(ele,no,stepTime){
$({someValue: 0}).animate({someValue: no}, {
        duration: stepTime,
        step: function() { // called on every step. Update the element's text with value:
            ele.text(Math.floor(this.someValue+1));
        },
        complete : function(){
            ele.text(no);
        }
});
}

animateNumber($('#counterx'),100,10000);
animateNumber($('#countery'),100,1000)
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
counterx(slow): <span id=counterx>--</span>
<br/>
countery(fast): <span id=countery>--</span>
Run Code Online (Sandbox Code Playgroud)