I want to change the background color of the fixed header after scrolling one screen.

html content
  Header fixed with Position: fixed.
    First view of height 100vh enters.
  The following contents are included.

On the other hand, I tried to write the following jquery, but it didn't work.
Specifically, when main came to the top of the page, I thought to change the background color by giving class ='bback'to the header.

script content
$(function () {
    $(window) .scroll (function () {
        var top_count = $(document) .scrollTop ();
        var main_count = $('main'). offset (). top;
        if (main_count<top_count) {
            console.log (main_count);
            $('header'). addClass ('bback');
        } else {
            $('header'). removeClass ('bback');

css contents

header {
    height: 50px;
    position: fixed;
    z-index: 1000;
    width: 100%;
    min-width: 320px;
    top: 0;
    left: 0;
header.bback {
    background: rgba (0,0,0,0.5);
#contents {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    min-height: 100vh;
    overflow-y: scroll;
    width: 100%;
#top {
    background: # 000;
    width: 100%;
    height: 100vh;
    overflow: hidden;
    position: relative;
main {
    padding: 0.5rem;
    min-height: calc (100vh-300px);/* Specify for fixing footer * /

The jQuery version is 2.24.
Please tell me how to solve it.

  • Answer # 1


    contents is also position: fixed;
    If you want to scroll with conetnts, you have to change the target.

    $('# contents') [0] .addEventListener ('scroll', function (event) {
        // Process.
      }, {passive: true});

Related articles