简体   繁体   中英

jQuery scrollTop() executes multiple times

I have a code like below in my Javascript (jQuery) file:

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%");
    }
});

And when I scroll 3 times in my browser something strange happens. Function fires multiple times (infinite). Then when I scroll top or down it works fine. Why is my scroll function causing infinite executes in a specyfic place?

The scoll event fires multiple times - that's the expected behavior. You should use the throttle/debounce ( https://underscorejs.org/#throttle ) functions to tackle this problem.

From 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在同一元素上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM