简体   繁体   中英

Using jQuery to change rgba background color when user scrolls

I have a navbar in which I would like the rgba background color to be changed when the user scrolls down, I would also like it to return to its original rgba color when the user scrolls back to the top of the screen. I am trying to use .animate as I would like the background change to ease in and out, however the .animate function does not seem to do anything at all and there are no errors on the console??

I cannot seem to find a clear and clean answer on this, so any help/advice would be great.

$(document).ready(function(){
    var scroll_pos = 0;
        $(document).scroll(function() { 
            scroll_pos = $(this).scrollTop();
            if(scroll_pos > 50) {
                $(".navbar").animate({'background-color': 'rgba(255, 255, 255, 0.5)'}, 3000);
            } else {
                $(".navbar").animate({'background-color': 'rgba(0, 0, 0, 0)'}, 3000);
            }
        });
});

Don't use animation. Set a transition via CSS to the navbar like this

.navbar { transition: background-color 1s; }

And change via JS the backgroundcolor

$(document).ready(function(){
    //var scroll_pos = 0; // you don't need this
        $(document).scroll(function() { 
            //scroll_pos = $(this).scrollTop();
            if(scroll_pos > $(this).scrollTop()) {
                $(".navbar").css('background-color', 'rgba(255, 255, 255, 0.5)');
            } else {
                $(".navbar").css('background-color', 'rgba(0, 0, 0, 0)');
            }
        });
});

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