我编写了这段代码来计算到页面顶部的距离。根据距离是否为 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/