简体   繁体   中英

How can I change the background colour of my menu when i scroll down?

I'm a pure student's beginner, right now I'm trying to create an adaptive menu for my project, but I need to change the color of my background because white on white is a little bit problematic.

What I tried is to create a script in order to add a class 'scroll' to my 'nav' when I'm scrolling down, and removed it when I'm going back to the top.

But as I said I'm a beginner, and it seems I did something wrong with either my script or my CSS.

Can you help me to understand how where I did something wrong?

Thanks for the help !

PS: Sorry for my english I did my best.

`https://codepen.io/Raz7/pen/zYKoJzY`

it's completly messed up, probably due to all the image I put in.

In your script tag you are using a JQuery Selector "$" but you did not add the JQuery library.

To keep things simple I will use the built-in querySelector from the document object and Vanilla Javascript.

The following code will do what you want:

let timeout;

window.addEventListener('scroll', function (e) {

    // If there's a timer, cancel it
    if (timeout) {
        window.cancelAnimationFrame(timeout);
    }

    // Setup the new requestAnimationFrame()
    timeout = window.requestAnimationFrame(function () {

        // Run our scroll functions
        let nav = document.querySelector('nav');

        if (document.querySelector('header').getBoundingClientRect().top !== 0) {
            nav.classList.add('scroll');
        } else {
            nav.classList.remove('scroll');
        }      
    });
}, false);
 

To actually know what the distance to the top is you need a point of reference, in this script I used the header element as a point of reference since the header is relative to the body tag. If the header distance to top is not 0 then add the scroll class to the nav element else remove it. You can see also a timeout and requestAnimationFrame, this helps de-bouncing the scroll event.

Instead of using the JQuery Library, if you are a beginner I suggest learning about Vanilla Javascript and the DOM.

https://www.w3schools.com/js/js_htmldom.asp

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