JQuery .scrollTop() 计算的长时间延迟

标签 jquery delay scrolltop

我编写了这段代码来计算到页面顶部的距离。根据距离是否为 0,它会使图像消失/出现,并向上/向下移动辅助图像。

$(window).scroll(function(){
    if ($(this).scrollTop() > 0) {
        $('#headerImg').animate({height:'0px'}, 500);
        $('#wrapperSCNav').animate({top:'185px'}, 500);
    } else {
        $('#headerImg').animate({height:'290px'}, 500);
        $('#wrapperSCNav').animate({top:'475px'}, 500);
    }
});

这有点有效,我很确定问题是代码计算scrollTop()太多次,以至于需要几秒钟的时间才能意识到它回到了0。

最佳答案

您应该考虑限制滚动功能,使其在设定的时间间隔后触发,而不是每秒触发数十次。我一直推荐使用Ben Alman's plugin .

对代码的修改将非常小 - 在下面的代码中,我选择限制滚动事件,使其每 250 毫秒触发一次(或每秒 4 次)。您当然可以调整这个值。

$(window).scroll($.throttle(250, function(){ // Use $.throttle() before calling function
    if ($(this).scrollTop() > 0) {
        $('#headerImg').animate({height:'0px'}, 500);
        $('#wrapperSCNav').animate({top:'185px'}, 500);
    } else {
        $('#headerImg').animate({height:'290px'}, 500);
        $('#wrapperSCNav').animate({top:'475px'}, 500);
    }
})); // Extra closing parenthesis from $.throttle()

顺便说一句,在使用 .stop(true,true) 触发每个动画之前强制清除动画队列并跳转到结束状态可能也是一个好主意:

$(window).scroll($.throttle(250, function(){ // Use $.throttle() before calling function
    if ($(this).scrollTop() > 0) {
        $('#headerImg').stop(true,true).animate({height:'0px'}, 500);
        $('#wrapperSCNav').stop(true,true).animate({top:'185px'}, 500);
    } else {
        $('#headerImg').stop(true,true).animate({height:'290px'}, 500);
        $('#wrapperSCNav').stop(true,true).animate({top:'475px'}, 500);
    }
})); // Extra closing parenthesis from $.throttle()

关于JQuery .scrollTop() 计算的长时间延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20790280/

相关文章:

当鼠标悬停在其他特定元素上时,jQuery 显示不同的元素(div)

javascript - 如何延迟基本的 HTML 工具提示?

点击时的 jQuery 延迟功能

jquery - 使用带有固定导航功能的scrollTop 的iPad 无法正常工作。仅第一次有效

javascript - 范围更改时更改按钮颜色

javascript - jQuery:使用 ToggleClass 编写 super 菜单

javascript - 如何制作 knockout 以在页面加载时填充数据

android延迟使用处理程序

javascript - jQuery 视差导航不会滚动到目标

Javascript Jquery ScrollTop 配对元素