jQuery动画意外滞后

时间:2014-04-10 18:43:36

标签: javascript jquery animation

我正在尝试使用jQuery创建一个“悬停”效果。 它工作正常,只是在第一次调用完整回调时出现奇怪的延迟 - 我注意到它只是 时间它实际到达它应该的确切位置(其余是〜1px较少,但那是好的),在那里呆一会儿,然后继续动画,从那时起它就能顺利进行。

我用我的代码here创建了一个jsFiddle,这是我写的代码。

function hover(el, speed, start, stop) {
    if (el.is(':visible')) {
        el.animate({
            'top': stop + 'px'
        }, speed, function () {
            el.animate({
                'top': start + 'px'
            }, speed, hover(el, speed, start, stop));
        });
    }
}

$("div > div").fadeIn(1000, function () {
    hover($(this), 1000, 192, 210);
});

我错过了一些明显的东西吗?这是一个错误吗?我滥用了什么吗?

感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

导致滞后是因为在hover()函数的第二次调用中你的元素已经位于顶部:210px所以它只是等待1秒没有任何东西,修复这个只是在你的函数中切换开始和停止点

function hover(el, speed, start, stop) {
    if (el.is(':visible')) {
        el.animate({
            'top': start + 'px'
        }, speed, function () {
            el.animate({
                'top': stop + 'px'
            }, speed, hover(el, speed, start, stop));
        });
    }
}

因此滞后将在开始时并且不会被注意到

编辑

解决方法是在第一时间给它一个启动:

var firstTime = true ; //this is global
function hover(el, speed, start, stop) {
    if (el.is(':visible')) {
        el.animate({
            'top': start + 'px'
        }, speed, function () {
            if(firstTime){
            el.animate({'top' : stop +"px" } , speed , function(){
                //something here 
            });
            firstTime = false; 
        }
        el.animate({
                'top': stop + 'px'
            }, speed, hover(el, speed, start , stop));
        });
    }
}

答案 1 :(得分:1)

您可以使用CSS动画

执行此操作
@-webkit-keyframes oscillation {
    from { top:192px; }
    to{ top:210px; }
}

@-moz-keyframes oscillation {
    from { top:192px; }
    to{ top:210px; }
}

然后将其放入您的div > div的CSS中:

-webkit-animation: oscillation 1s ease-in-out infinite alternate;
-moz-animation: oscillation 1s ease-in-out infinite alternate;

演示:http://jsfiddle.net/howderek/F4dkB/3/