Skip to main content
 首页 » 编程设计

jQuery:如何改进这个被触发太多次的滚动事件

2026年09月08日2tuyile006

这段代码可以工作并且可以完成工作,但是它非常差+简陋,并且在滚动事件方面存在一些问题。有人可以帮我优化滚动事件吗?

原型(prototype):http://codepen.io/rootion/pen/gpZZpG

结构和期望的行为:

  • 有两个容器:.layout__left(红色)和.layout__right(绿色)。
  • 绿色容器将包含主要内容并正常滚动。
  • 红色容器将具有导航功能,因此内容较少,并且只能向上滚动到某个点,直到菜单到达页面边框。

这就是我正在做的事情:

  1. 首先,两个容器都正常滚动。
  2. 向下滚动红色容器时,如果滚动位置 + 窗口大小大于 li:last 子位置(无法想到检测“底部”),则容器的位置固定。
  3. 向上滚动时,固定位置会被禁用,当菜单到达文档顶部时,位置会再次固定,然后删除。

正如我所说,这可以完成任务。但速度很慢,并且滚动时会出现故障。我认为这是因为我正在执行滚动事件并且它在每个像素中执行。

我尝试限制函数调用,但代码根本不起作用:

    $(window).on('scroll', function() { 
    $.throttle(100, sectionScroll)); 
    }); 
 
    sectionScroll = function() { 
    var lastScrollTop = 0, delta = 5; 
    var left = $('.layout__left'); 
    var right = $('.layout__right'); 
    var scroll = $(this).scrollTop(); 
    var viewport = $(window).height(); 
    var lastChild = $('.navigation > ul > li:last-child').offset().top; 
 
    if(Math.abs(lastScrollTop - scroll) <= delta) 
    return; 
 
    if (scroll > lastScrollTop){ 
    // SCROLL DOWN 
    left.removeClass('top absolute'); 
 
    // if the last item of the left is visible 
    if (  (scroll + viewport) > (lastChild + 30)  ) { 
    // make the left fixed 
    left.addClass('fixed bottom'); 
    console.log("bottom!"); 
    } 
 
    // SCROLL UP 
    } else { 
    // remove fixed class from left 
    left.removeClass('fixed bottom'); 
    left.addClass('absolute bottom'); 
 
    if ( scroll <= left.position().top   ) { 
    left.removeClass('bottom absolute'); 
    left.addClass('top fixed'); 
    left.removeClass('top fixed'); 
    console.log("top!"); 
    } 
    } 
 
    lastScrollTop = scroll; 
    }; 

有任何反馈吗?

请您参考如下方法:

一种方法是将其放在脚本中的某个位置:

var isStarted = false; 

然后,在您的启动函数中:

if(!isStarted) { 
    isStarted = true; 
//other stuff 
} else { 
    return false; //because it's already doing it's thing 
} 

在你的停止函数中:

isStarted = false;