window.scroll函数冻结了firefox

Dan*_*iel 5 firefox jquery scroll freeze

我正在处理一个带有固定菜单的页面,该菜单在用户从顶部滚动一定距离后拾取,当它们向下滚动页面时,菜单中的不同链接将被赋予一个更改颜色的类.所有这一切似乎都适用于Chrome和Safari,但在Firefox中,页面冻结在顶部.我想知道它是否在不断地循环一些代码......基本上冻结了窗口.

这是我的代码.

$.localScroll({
    onBefore: function() {
        $('body').data('scroll-executing', true);

    },
    onAfter: function() {
        $('body').data('scroll-executing', false);
        $(window).trigger("scroll");
    }
});

$(window).scroll(function () {
    if ($(this).scrollTop() > 259) {
        $('.nav').addClass("f-nav");
    } else {
        $('.nav').removeClass("f-nav");
    }
});

$(window).scroll(function() { 
    if ($('body').data('scroll-executing')) {
        return;
    }
    // find the a with class 'active' and remove it
    $("a").removeClass('active');
    // get the amount the window has scrolled
    var scroll = $(window).scrollTop();
    // add the 'active' class to the correct #nav based on the scroll amount

    if (scroll > 2150) {
        $("#nav_3").removeClass('active');
        $("#nav_5").attr('class', 'active');
        setHash("contact");

    } else if (scroll > 1300) {
        $("#nav_2").removeClass('active');
        $("#nav_3").attr('class', 'active');
        setHash("portfolio");

    } else if (scroll > 400) {
        $("#nav_2").attr('class', 'active');
        setHash("about");

    } else if (scroll <= 380) { //when I remove this section, the problem goes away.
        $("#nav_1").attr('class', 'active');
        setHash("home");
    }

});
Run Code Online (Sandbox Code Playgroud)

我忘了添加setHash定义.这里是.

setHash = function(hash) {
    var scrollmem = $('body').scrollTop();
    window.location.hash = hash;
    $('html,body').scrollTop(scrollmem);
}
Run Code Online (Sandbox Code Playgroud)

我也注意到CPU上升到100%,我似乎无法弄清楚原因.

问题出现在以else开头的代码的第三部分if(scroll <= 380).我通过消除过程想出来了.任何人都可以看到它循环或做一些永远不会结束的事情......或者会解释为什么firefox冻结在页面顶部?

我对这一切都很陌生......在过去的几天里我只是选择了jquery,我基本上都在谷歌上搜索并调整代码以使其符合我的需要.

任何帮助将非常感激.

und*_*ned 3

在滚动事件上执行太多代码是多余的,在每次滚动时,浏览器都会触发滚动事件数百次,您可以考虑使用具有类似throttle或 之类的方法的库debounce

http://documentcloud.github.com/underscore/#throttle

将处理程序附加到窗口滚动事件是一个非常非常糟糕的主意。根据浏览器的不同,滚动事件可能会触发很多次,并且将代码放入滚动回调中会减慢任何滚动页面的尝试(这不是一个好主意)。因此,滚动处理程序中的任何性能下降只会加剧整体滚动的性能。相反,最好使用某种形式的计时器每 X 毫秒检查一次或附加滚动事件并仅在延迟后运行代码(或者甚至在给定的执行次数之后 - 然后延迟)。 http://ejohn.org/blog/learning-from-twitter/