我的 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/