【问题标题】:setInterval counter with jQuery animate带有 jQ​​uery 动画的 setInterval 计数器
【发布时间】:2014-02-26 18:03:03
【问题描述】:

我正在开发一个距离的伪时间线,并带有一个工具提示,该工具提示会跟随时间线到达新的标记位置。

 |--------- 800px ------|------------------- 1200px ----------- |
 A (5000km)             B (20000km)                             C (30000km)

标记 A(5000 公里)和标记 B 之间是 15000 公里的虚假差异,但时间轴上元素之间的实际距离是 800 像素。我用一个计数器为指示器设置动画,该计数器在 12 秒内沿着这两个点移动。动画很简单,但我无法计算出计数器间隔,因此它在 12 秒的时间范围内从 5000 开始到 20000 结束。

这就是我所拥有的,但是由于我无法求解增量值,所以计数器在动画后面完成了。

var ttl = 12*1000,
    startKM = 5000,
    endKM = 15000,
    diffDist = endKM-startKM,
    distanceLoop,
    txt = $('.counter').text();
    increment = diffDist/ttl;

$('.counter').text(startKM);

$('.indicator').animate({ left: $('.markB').offset().left }, ttl, 'linear', function() {
    clearInterval(distanceLoop);
});

function counterLoop() {

    var num = txt++;
    // what is the count interval 
    // var num = txt + increment
    $('.counter').text(num);
};

distanceLoop = setInterval(counterLoop, diffDist/ttl )

counterLoop();

我不知道增量是什么,所以现在它只是对计数器 +1。这可能是一些基本的东西,我只是没有看到。

感谢您的帮助!

演示/小提琴:http://jsfiddle.net/7xygy/10/

【问题讨论】:

    标签: jquery time jquery-animate setinterval


    【解决方案1】:

    您可以使用.animate() 函数的step 选项,而不是setInterval

    var startKM = 5000,
        endKM = 15000;
    
    var startLeft = $('.indicator').offset().left,
        endLeft = $('.markB').offset().left,
        ratio = (endKM - startKM) / (endLeft - startLeft);
    
    $('.counter').text(startKM);
    $('.indicator').animate({ left: endLeft }, {
        easing: 'linear',
        duration: 12000,
        step: function(now) {
            $('.counter').text(Math.floor(startKM + ((now - startLeft) * ratio)));
        },
        complete: function() {
            $('.counter').text(endKM);
        }
    });
    

    jsfiddle

    【讨论】:

    • 对此我很头疼。太棒了:)
    • 干得好,约翰!我不知道步骤回调,因为我知道 setInterval 不是 100% 准确,所以效果要好得多。在一个版本中,我有你的比例,但我应该坚持下去。干杯!
    猜你喜欢
    • 2013-02-03
    • 1970-01-01
    • 2017-04-04
    • 2015-08-12
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多