如何在Javascript中显示运行计数器?
我有一个包含数值的表格单元格。
更改值时,我想创建一种效果,其中计数器向上(或向下)移动 100 步,直到达到新值。
我尝试过类似以下的方法(在 jQuery 的帮助下): <代码> <代码>
function update(element,newValue)
{
var oldValue = parseFloat($(element).text());
var diff = (newValue - oldValue) / 100;
for (var i = 0; i < 100; i++) {
oldValue += diff;
$(element).text(oldValue);
}
}
> 然而,Javascript 似乎不会刷新显示,直到脚本完成后 - 因此没有效果。
如何确保每一步都显示中间值?
I have a table cell that contains a numerical value.
When changing the value, I want to create an effect where the counter moves up (or down) in 100 steps until reaching the new value.
I've tried something like the following (with the help of jQuery):
function update(element,newValue) { var oldValue = parseFloat($(element).text()); var diff = (newValue - oldValue) / 100; for (var i = 0; i < 100; i++) { oldValue += diff; $(element).text(oldValue); } }
However, Javascript doesn't seem to refresh the display until AFTER the script is done - thus there's no effect.
How do I make sure the intermediate values are displayed at each step?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西非常面向 jQuery:
现在只需使用:
它将计数到 1 到 100,数字每 100 毫秒递增一次。间隔是可选的第三个参数。
Something like this is very jQuery orientated:
Now just use:
Which will count to 1 to 100, with the number incrementing every 100 ms. The interval is an optional 3rd parameter.
JavaScript 和 DOM 共享同一个线程,因此当脚本当前正在执行时,显示无法刷新。它必须等到线程空闲。您只能使用 setTimeout 或 < a href="https://developer.mozilla.org/en/DOM/window.setInterval" rel="nofollow noreferrer">setInterval 调用,用计时器而不是循环增加每个步骤。
JavaScript and the DOM share the same thread, so the display cannot refresh whilst script is currently executing. It has to wait until the thread becomes idle. You can only achieve what you're trying to do with a setTimeout or setInterval call, increasing each step with a timer instead of a loop.
不确定 JQuery 方面的情况,但这里有一个快速示例页面:
Not sure about the JQuery side of things, but here's a quick sample page: