jQuery scrollTop() 执行了多次
jQuery scrollTop() executes multiple times
我的 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.
我解决了我的问题,即在同一元素上使用 display: flex 和 position:fixed。
我的 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.
我解决了我的问题,即在同一元素上使用 display: flex 和 position:fixed。