且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery对scrollTop()的响应很慢

更新时间:2023-12-06 08:12:52

问题在于 .animate()每次调用时都会添加到队列中。因此,当您从顶部滚动时,另一个动画将添加到每个滚动事件的动画队列中。然后当你回到顶部时, .animate({height:'140px'},500)动画将被添加到队列的末尾,这意味着它'只有在所有其他动画都发生后才会出现(每个动画需要500毫秒)。当然,你没有看到这些其他的动画发生,因为你告诉jQuery动画他们已经拥有的值,因此没有任何视觉效果。

The problem is that .animate() adds to a queue each time it's called. So as you scroll away from the top, another animation is getting added to the animation queue for every scroll event. Then when you do get back to the top, the .animate({height:'140px'}, 500) animation is getting added to the end of the queue meaning it'll only occur once all the other animations have happened (each taking 500 milliseconds). Of course, you don't see these other animations taking place because you're telling jQuery to animate to the values that they already have, and therefore there's nothing visually happening.

http://api.jquery.com/animate/

尝试:

var atTop = !$(document).scrollTop();

$(window).scroll(function () {

    if ($(document).scrollTop() === 0 && !atTop) {

        $('#nav.header').animate({height:'140px'}, 500);
        $('ul.right').animate({'line-height':'140px'}, 500);

        atTop = true;

    } else if (atTop) {

        $('#nav.header').animate({height:'40px'}, 500);
        $('ul.right').animate({'line-height':'40px'}, 500);

        atTop = false;

    }
});

http://jsfiddle.net/4DK3F/32/