首页 > 解决方案 > 滚动时更改颜色

问题描述

我一直在寻找解决方案,但我无法让它工作。

当用户开始滚动页面时,我希望我的页眉从透明背景变为红色背景。

$(window).on("scroll", function() {
    if($(window).scrollTop() > 800) {
        $(".header").addClass("active");
    } else {
       $(".header").removeClass("active");
    }
});
* {margin:0;padding:0}

html {
    background: lightgray;
    height: 5000px;
}

.header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    padding: 0;
    z-index: 10000;
    transition: all 1s ease-in-out;
    height: auto;
    background-color: rgba(17, 42, 107, 0.7);
    
    text-align: center;
    line-height: 40px;
}

.header.active {
    background: red;
    -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
    -moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">the header</div>

标签: javascripthtmlcss

解决方案


$(window).scroll(function () {
    var scroll = $(window).scrollTop();
    console.log(scroll);
    if (scroll >= 10) {
        $(".header").addClass("active");
    } else {
        $(".header").removeClass("active");
    }
});

推荐阅读