简体   繁体   English

滚动时导航更改背景的粘性 position position

[英]Sticky position of nav change background at scroll position

I want the <nav> to be fixed with the 3 numbers.我希望<nav>用 3 个数字固定。 When it reaches the green square, it should go OVER the numbers and stay fixed and turn red.当它到达绿色方块时,它应该 go 超过数字并保持固定并变为红色。 And when you go back to the top, it should go back to it's original position and go back to green.当你 go 回到顶部时,它应该 go 回到原来的 position 和 Z34D6BZ561FB2E75A8B8 回到绿色。 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 .要更改背景颜色,您需要查看animation方式,但是,根据定位,您需要添加类似top: 0的内容来设置 position 您的组件会

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: 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工作片段:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM