$(window).scroll not fast enough to process my jquery?

拥有回忆 提交于 2021-02-08 10:55:54

问题


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: enter image description here But it should be down further: enter image description here

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!