jquery – window.scroll函数冻结了firefox

前端之家收集整理的这篇文章主要介绍了jquery – window.scroll函数冻结了firefox前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在处理一个带有固定菜单页面,该菜单用户从顶部滚动一定距离后拾取,当它们向下滚动页面时,菜单中的不同链接将被赋予一个更改颜色的类.所有这一切似乎都适用于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");
    }

});

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

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

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

问题出现在以else开头的代码的第三部分if(scroll< = 380).我通过消除过程想出来了.任何人都可以看到它循环或做一些永远不会结束的事情......或者会解释为什么firefox冻结在页面顶部? 我对这一切都很陌生……在过去的几天里我只是选择了jquery,我基本上都在谷歌上搜索并调整代码以使其符合我的需要. 任何帮助将非常感激.

最佳答案
在滚动事件上执行太多代码是过度的,在每个滚动上,浏览器触发滚动事件一百次,您可以考虑使用具有诸如油门或去抖等方法的库.

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

It’s a very,very,bad idea to attach handlers to the window scroll event. Depending upon the browser the scroll event can fire a lot and putting code in the scroll callback will slow down any attempts to scroll the page (not a good idea). Any performance degradation in the scroll handler(s) as a result will only compound the performance of scrolling overall. Instead it’s much better to use some form of a timer to check every X milliseconds OR to attach a scroll event and only run your code after a delay (or even after a given number of executions – and then a delay).
07001

原文链接:https://www.f2er.com/jquery/428119.html

猜你在找的jQuery相关文章