简体   繁体   中英

Jquery scrolltop function not working on mobile

Im creating a navbar that will fade in when I scroll a little bit down the page. My code works fine on desktop, but it does not work when I switch to mobile.

Here is the javascript:

 $(document).ready(function(){
    $(window).bind('scroll', function() {
        var distance = 100;

        if ($(window).scrollTop() > 50) {
            $('nav').css("background-color","rgba(6, 14, 49, 0.94)");
        }
        else {
          $('nav').css("background-color","rgba(6, 14, 49, 0.50)");
        }
   });
});

Thanks for any and all suggestions. I already tried switching $(window) to $('body') or $('html') and they didnt work

You can use $().scroll method to implement the desired result.

$(window).scroll(function() {  
      var distance = 50;
        if ($(window).scrollTop() > 50) {
            $('nav').css("background-color","rgba(6, 14, 49, 0.94)");
        }
        else {
          $('nav').css("background-color","rgba(6, 14, 49, 0.50)");
        }
   });      
});

On mobile, the "scroll" event will be fired only when the scroll stops. for example, if you have a big slide on your mobile phone, and the window keep scrolling for 5 seconds, then the scroll event will be fired after 5 seconds.

Therefore, unfortunately, you cannot monitor the offset while the window is scrolling.

as an alternative, try to check some plugin that fake the scrolling which allow you to "monitor" the offset while "scrolling" . eg : https://github.com/cubiq/iscroll

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