javascript - jQuery的scrollTop()执行多次

标签 javascript jquery scrolltop

我的 Javascript (jQuery) 文件中有如下代码:

jQuery(document).on('scroll', function() {
    var scrollTop = jQuery(document).scrollTop();
    console.log(scrollTop);
    if(scrollTop < 350) {
        jQuery('.header__top').removeClass('header-fixed');
        jQuery('.logo').css({position: "absolute", height: "auto"});
        jQuery('.logo img').css("height", "auto");
    }else {
        jQuery('.header__top').addClass('header-fixed');
        jQuery('.logo').css({position: "static", height: "85px"});
        jQuery('.logo img').css("height", "100%");
    }
});

当我在浏览器中滚动 3 次时,会发生一些奇怪的事情。函数触发多次(无限次)。然后当我向上或向下滚动时它工作正常。为什么我的滚动函数会在特定位置导致无限执行?

最佳答案

scoll 事件触发多次 - 这是预期的行为。您应该使用throttle/debounce ( https://underscorejs.org/#throttle ) 函数来解决这个问题。

来自 MDN:

Since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame(), setTimeout() or a CustomEvent, as follows.

关于javascript - jQuery的scrollTop()执行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53822898/

相关文章:

javascript - 为什么形状选择偏移?

jquery - 如何停止 jQuery SlideToggle 溜溜球?

javascript - 仅在选择框第二次更改后才触发更改上的 JQuery

jquery移动: navbar not keeping active state

javascript - scrollTop 等于 0,即使 div 位于页面下方

javascript - HTML5 Canvas - 在 Canvas 上绘图、保存上下文并稍后恢复

javascript - 使用 Hooks 在 React 中实现倒计时器

jquery - ;Jquery : animate page down 100px from current screen position

javascript - 如何在页面加载事件之后立即获得页面的 scrollTop?

javascript - 无法获取未定义或空引用的属性