jQuery对scrollTop()的响应很慢 [英] jQuery slow response to scrollTop()

查看:496
本文介绍了jQuery对scrollTop()的响应很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力调整高度导航,如下所示: http:// www .kriesi.at / themes / enfold /

I've been trying to make a resizing height navigation, as seen here: http://www.kriesi.at/themes/enfold/

我在jsfiddle上看到的非常接近: http://jsfiddle.net/magnusbrad/4DK3F/12/

I've gotten very close as seen here on jsfiddle: http://jsfiddle.net/magnusbrad/4DK3F/12/

<div id="nav" class="header">
nav here
<ul class="right">
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>
</div>

$(window).scroll(function () {
if ($(document).scrollTop() === 0) {
    $('#nav.header').animate({height:'140px'}, 500);
    $('ul.right').animate({'line-height':'140px'}, 500);
} else {
    $('#nav.header').animate({height:'40px'}, 500);
    $('ul.right').animate({'line-height':'40px'}, 500);
}
});

当您向下滚动时,动画效果很好,但是当您向后滚动到页面顶部时更新并运行else语句需要10秒钟。我错过了什么让这个动作实时更快地发生?

When you scroll down the animation works perfectly, however, when you scroll back to the top of the page it takes like 10 seconds to update and run the else statement. What am I missing to make that action happen faster, in real time?

推荐答案

问题在于 .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/

这篇关于jQuery对scrollTop()的响应很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆