angular - 在没有 jquery 的情况下向下滚动时,粘性菜单会改变颜色

标签 angular html css flexbox

我的 angular 6 元素中有一个 flexbox 导航菜单,我想在菜单粘在顶部时更改背景颜色。

这是我想要的[示例], Expected result

这是我目前所拥有的:

sticky menu on scroll

这是使用 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/

相关文章:

angular - EACCES 权限被拒绝在 docker 中进行 angular cli ng 构建

jquery - 单击下拉菜单时 bootstrap3 导航关闭

javascript - 如何使用此脚本创建多个插入文本区域的按钮

html - 如果缺少其他 div,则扩展 div 宽度

css - 如何在 LESS 中有效地编写 -sm、-md、-lg 填充类

Angular JWT Token 添加到 lazyUpdate 而不是 HttpHeaders 中的 header

javascript - 获取地理点时出现 typescript 错误,意外的 ','

angular - 将 Angular 5 中的 Http 升级到 HttpClient : "server responded with a status of 415 (Unsupported Media Type)"

jquery - 是什么让下拉菜单覆盖其他元素?

html - 通过 virtual box/ubuntu 使用 godaddy 域运行在线网站