$(window).scroll 不够快来处理我的 jquery? [英] $(window).scroll not fast enough to process my jquery?

查看:64
本文介绍了$(window).scroll 不够快来处理我的 jquery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在滚动窗口时遇到问题,我认为事件触发太快而无法处理.

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()
        }); 

推荐答案

.scroll 声明移到航点声明之外.

Move the .scroll declaration outside the waypoint declaration.

然后使用 lodash .throttle 来限制执行次数.此外,让我们缓存 jQuery 窗口对象.

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
 });

限制为 16ms 是一个很好的经验法则,因为它是 60hz 显示器的刷新率,而且用户不会注意到任何比 16ms 快的东西.

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.

这篇关于$(window).scroll 不够快来处理我的 jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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