问题
Im having an issue with window scrolling where I think events are firing too quickly to process.
Im using waypoints to detect when a subnav on my page hits the header when scrolling, and when it does it pushes the header up off the page. And when scrolling back up, the header gets pulled down into its original position. Now the first part works flawlessly, the head gets pushed up, but pulling it back down is very buggy. Scrolling too quickly results in the header getting stuck on the way.
It gets stuck like this: But it should be down further:
It will work if you scroll slowly, but realistically its not cutting it. Unfortunately the site is not yet public so I cant link to it just yet.
$('.subnav-wrapper').waypoint(function(direction) {
var $headerWrapper = $('.header-wrapper');
var headerHeight = $headerWrapper.outerHeight();
$(window).scroll(function() {
var scrollHeight = $(this).scrollTop();
if( scrollHeight >= 400 ) {
$headerWrapper.css( 'margin-top', ( scrollHeight - 400 ) * -1 );
}
});
},
{
offset: $('.header-wrapper').outerHeight()
});
回答1:
Move the .scroll
declaration outside the waypoint declaration.
Then use lodash .throttle to limit the number of executions. Also, lets cache the jQuery window object.
var $window = $(window);
$window.scroll(_.throttle(function () {
var scrollHeight = $window.scrollTop();
if (scrollHeight >= 400) {
$headerWrapper.css('margin-top', (scrollHeight - 400) * -1);
}
}, 16), {
trailing: true
});
Limiting to 16ms is a good rule of thumb because its the refresh rate of a 60hz monitor, and users wont notice anything faster than 16ms anyway.
来源:https://stackoverflow.com/questions/21005354/window-scroll-not-fast-enough-to-process-my-jquery