jquery – window.scroll函数冻结了firefox

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

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

这是我的代码.

  1. $.localScroll({
  2. onBefore: function() {
  3. $('body').data('scroll-executing',true);
  4. },onAfter: function() {
  5. $('body').data('scroll-executing',false);
  6. $(window).trigger("scroll");
  7. }
  8. });
  9. $(window).scroll(function () {
  10. if ($(this).scrollTop() > 259) {
  11. $('.nav').addClass("f-nav");
  12. } else {
  13. $('.nav').removeClass("f-nav");
  14. }
  15. });
  16. $(window).scroll(function() {
  17. if ($('body').data('scroll-executing')) {
  18. return;
  19. }
  20. // find the a with class 'active' and remove it
  21. $("a").removeClass('active');
  22. // get the amount the window has scrolled
  23. var scroll = $(window).scrollTop();
  24. // add the 'active' class to the correct #nav based on the scroll amount
  25. if (scroll > 2150) {
  26. $("#nav_3").removeClass('active');
  27. $("#nav_5").attr('class','active');
  28. setHash("contact");
  29. } else if (scroll > 1300) {
  30. $("#nav_2").removeClass('active');
  31. $("#nav_3").attr('class','active');
  32. setHash("portfolio");
  33. } else if (scroll > 400) {
  34. $("#nav_2").attr('class','active');
  35. setHash("about");
  36. } else if (scroll <= 380) { //when I remove this section,the problem goes away.
  37. $("#nav_1").attr('class','active');
  38. setHash("home");
  39. }
  40. });

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

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

我也注意到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

猜你在找的jQuery相关文章