Change header background colour when page scrolls

前端 未结 1 1646
太阳男子
太阳男子 2020-12-13 07:59

I\'ve been looking at a solution for this but I cannot get it to work.

I would like my page header to change from a transparent background to a white background as t

相关标签:
1条回答
  • 2020-12-13 08:08
    $(window).on("scroll", function() {
        if($(window).scrollTop() > 50) {
            $(".header").addClass("active");
        } else {
            //remove the background property so it comes transparent again (defined in your css)
           $(".header").removeClass("active");
        }
    });
    

    fiddle: http://jsfiddle.net/634d6vgq/2/

    This will add the background-color: #fff to the element if user has scrolled more than 50 pixels from the top

    This will add a class "active" so you can style it within the css (easier to maintain)

    edit:

    $(function() {
        $(window).on("scroll", function() {
            if($(window).scrollTop() > 50) {
                $(".header").addClass("active");
            } else {
                //remove the background property so it comes transparent again (defined in your css)
               $(".header").removeClass("active");
            }
        });
    });
    

    And your css:

    .active { background-color: #fff}
    

    Make sure you also add this css rule, orherwise the background color will not change

    0 讨论(0)
提交回复
热议问题