我正在尝试使用以下代码在文本框中递增数字
// 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));
}
});它处理的是像从1099933到1099610这样的小数字,但是当涉及到像前面提到的代码中的大数字时,它不是给出目标数字,而是动画到像100或100这样的数字.每次它改变的时候。
那么我怎样才能使它的动画效果达到我指定的数字呢?
发布于 2012-05-26 01:26:59
我也有同样的问题。这是因为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)<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>
发布于 2012-05-26 01:28:47
动画不是设计的将计数器作为文本递增的(尽管它可能会意外地工作,这可能会随任何新版本的jQuery而改变),它是设计的,用于动画一个或多个CSS属性。您应该改用setInterval。
http://jsfiddle.net/jbabey/mKa5r/
var num = 0;
var interval = setInterval(function () {
document.getElementById('result').innerHTML = num;
num++;
if (num === 100) {
clearInterval(interval);
}
}, 100);发布于 2012-05-26 01:48:01
1) Javascript是单线程应用程序。超时和动画仅根据理想的堆栈顺序将事件推送到堆栈的末尾。脚本的长时间运行可能会导致该事件的实际触发时间远远超出您所寻找的准确性。
2)动画近似增加多少,在较大的数字上,该分辨率非常不准确。
3) jQuery只有一个动画缓冲区。如果使用动画调用多个“计数器”,可能会遇到一些严重的渲染问题。在进行任何影响动画的调整之前,请确保停止上一个动画。
4)即使在超时为0的情况下,您也可以预期实际延迟为~15。即使这是您运行的唯一“线程”。
解决方案:
take a snapshot of the DTG
set your interval to something within the human experience, say ~200
on each interval, check how much time has passed from the original DTG
set your text field to that delta number.
stop the interval with the original DTG + "your target number" > the new DTGhttps://stackoverflow.com/questions/10758759
复制相似问题