Change header background colour when page scrolls

你说的曾经没有我的故事 提交于 2019-11-28 18:02:41
$(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!