jQuery动画意外滞后

jQuery animation unexpected lag

本文关键字:滞后 意外 动画 jQuery      更新时间:2023-09-26

我正在尝试创建一个;悬停";jQuery的效果。它工作得很好,只是第一次调用完整回调时出现了一个奇怪的滞后-我注意到这是唯一的时间,它实际上到达了它应该到达的确切位置(其余的大约少了1px,但这很好),在那里停留一段时间,然后继续动画,从那一点开始,它工作得顺利。

我在这里用代码创建了一个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);
});

我是不是错过了一些显而易见的东西?是虫子吗?我是不是滥用了什么?

感谢任何帮助,谢谢!

延迟是因为在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));
        });
    }
}

您可以使用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/