当前位置: 代码迷 >> JavaScript >> 在同一时间完成多个动画
  详细解决方案

在同一时间完成多个动画

热度:82   发布时间:2023-06-05 10:12:56.0

我有四个'.dist'元素。 它们具有不同的预加载数据(确切地说:57,27,17,244)。 我想动画递增,我写了这段代码:

$('.dist').each(function() {
    var count = parseInt($(this).text())
    var incr = 0
    var that = $(this)
    var animation_time = 500
    var interv = animation_time / count

    $(this).text('0')

    var fd = setInterval(function() {
        if (incr < count){
            incr++
            that.text(parseInt(incr))
        }
    } , interv)
    console.log(interv)
})

问题:最大价值在完成100光年后完成。

Console.log(直接来自此代码)返回:

8.928571428571429 18.51851851851852 29.41176470588235 2.0491803278688523

这是我/我们期望的值,但我认为每个间隔都有一个特定的延迟,但我不知道如何检测和纠正延迟。

我希望在时间?= 500ms内完成从0到'var count'的所有递增。 我想在同一时间开始所有的增量,并在同一时间完成每一个。

很抱歉我的原始问题,但我在6个月前开始使用js / jq冒险,我找不到谷歌的答案。 也许我已经开始了或者什么的。 感谢帮助。

编辑:html

<div class="info back2 border corners1">
        <span class="dist">56</span>  seriali<br>
        <span class="dist">27</span>  obejrzanych<br>
        <span class="dist">17</span>  oczekuje<br>
        <span class="dist">244</span>  sezonów<br>
</div>

你有两个问题:一个是你的间隔很小,第二个是计算的间隔变成一个浮点数。 SetInterval只能处理整个毫秒而不是分数,因此您的计算将始终处于关闭状态。 最好设置开始和结束时间并计算差异。

这是在Javascript中进行时间计算的最准确方法。

$('.dist').each(function() {
    var count = parseInt($(this).text());
    var incr = 0;
    var that = $(this);
    var animation_time = 500;

    $(this).text('0');
    var time_start = new Date();

    var fd = setInterval(function() {
        var time_passed = new Date() - time_start;
        if (time_passed >= animation_time) {
            clearInterval(fd);
            time_passed = animation_time;
        }
        that.text(Math.round(count*time_passed/animation_time));
    } , 10);
})

或者,如果您不关心动画的实际时间,并希望浏览器断断续续等不计入时间,您可以自己增加time_passed

如果您有一定数量的步数并按比例增加,那么您的计数将一起达到目的,同样不要忘记在动画完成后清除间隔。

clearInterval(fd);