我的 angular 6 元素中有一个 flexbox 导航菜单,我想在菜单粘在顶部时更改背景颜色。
这是我想要的[示例], Expected result
这是我目前所拥有的:
这是使用 position: sticky
的粘性菜单的 css
.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
我的代码中缺少什么?新手刚学
最佳答案
正如 Keno 所提到的,媒体查询中的 position: inherit
覆盖了 position: sticky
。
但是根据 MDN ( https://developer.mozilla.org/en-US/docs/Web/CSS/position ),使用 position: sticky
只会使相对于父窗口的“粘滞”而不是相对于窗口
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 ) 的 position: fixed
It is [the element] positioned relative to the initial containing block established by the viewport.
所以你的 CSS 应该是
.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;
}
至于在用户滚动时更改导航栏的颜色,您将需要 javascript 来检测滚动事件并相应地更改颜色。
关于angular - 在没有 jquery 的情况下向下滚动时,粘性菜单会改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51847812/