简体   繁体   中英

Sticky position of nav change background at scroll position

I want the <nav> to be fixed with the 3 numbers. When it reaches the green square, it should go OVER the numbers and stay fixed and turn red. And when you go back to the top, it should go back to it's original position and go back to green. How would I achieve this?

 .container { height: 1000px; } nav{ display: flex; justify-content: space-around; }.square{ background-color: green; width: 100px; height: 100px; margin: auto; display: block; position: sticky; }
 <div class="container"> <header> <nav> <p>1</p> <p>2</p> <p>3</p> </nav> </header> <div class="square"></div> </div>

For changing backgroung-color, you need to look in the animation way, but, according the positioning, you need to add something like top: 0 to set in what position you component will be sticky .

you can use javascript to detect scroll and use window.onscroll to add sticky class to your element, also note that when using sticky CSS attribute value for display you should also adjust the location, I used calc to calculate the left value, here is a working snippet:

 window.onscroll = function() {myFunction()}; var header = document.querySelector(".square"); var sticky = header.offsetTop; function myFunction() { if (window.pageYOffset > sticky) { header.classList.add("sticky"); } else { header.classList.remove("sticky"); } }
 .container { height: 10000px; } nav { display: flex; justify-content: space-around; }.square { background-color: green; width: 100px; height: 100px; margin: auto; display: block; }.sticky { position: fixed; top: 0; background-color:red; left: calc((100% - 100px)/2); }.sticky +.content { padding-top: 102px; }
 <,DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="container"> <header> <nav> <p>1</p> <p>2</p> <p>3</p> </nav> </header> <div class="square"></div> </div> </body> </html>

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