向下滚动而不使用jQuery时,粘性菜单会更改颜色 [英] Sticky menu changing color when scrolling down without jquery
问题描述
我的angular 6项目中有一个flexbox导航菜单,我想在菜单顶部粘稠时更改背景颜色.
I have a flexbox navigation menu in my angular 6 project , I want to change the background-color when the menu is sticky at the top .
这就是我想要的[样本], 预期结果
Here is what I would like to have [sample], Expected result
这是我到目前为止所拥有的:
Here is what I have so far :
这是使用position: sticky
.main-nav-sticky{
background-color: white;
}
.main-nav {
margin-top: 100px;
position: sticky;
align-items: center;
justify-content: space-around;
top: 0;
left: 0;
display: flex;
height: auto;
width: 100%;
color: green;
}
我只希望当用户滚动并且菜单位于顶部时,菜单的导航应该具有background-color: white
I just want when a user scroll and the menu is sticky at the top, the navigation the menu should have a background-color: white
我的代码中缺少什么?是新手吗?
what am I missing in my code? am newbie just learning
推荐答案
正如基诺(Keno)所述,您的媒体查询中的position: inherit
超出了position: sticky
.
As Keno mentioned, the position: inherit
in your media query is over riding position: sticky
.
但是根据MDN(
粘性定位元素是其计算的位置值具有粘性的元素.它被视为相对定位,直到其包含的块在其流根(或在其中滚动的容器)内超过指定的阈值(例如,将top设置为auto以外的值),在此点将其视为卡住",直到达到其包含块的相对边缘.
A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block. 为实现所需的行为,您应使用根据MDN( https://developer.mozilla.org/en-US/docs/Web/CSS/position ) For you to achieve the desired behavior the you should use 它是[元素]相对于视口建立的初始包含块的位置. It is [the element] positioned relative to the initial containing block established by the viewport. 因此您的CSS应该是 关于在用户滚动时更改导航栏的颜色,您将需要 javascript以检测滚动事件并相应地更改颜色. And as for changing the color of the navbar when the user scrolls, you are going to need javascript to detect the scroll event and change the colors accordingly. 这篇关于向下滚动而不使用jQuery时,粘性菜单会更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
position: fixed
which is according to MDN (https://developer.mozilla.org/en-US/docs/Web/CSS/position)
.main-nav-sticky {
background-color: white;
}
.main-nav {
margin-top: 100px;
position: fixed;
align-items: center;
justify-content: space-around;
top: 0;
left: 0;
display: flex;
height: auto;
width: 100%;
color: green;
}