我正在尝试制作一个导航栏重叠我的标题并在滚动时粘在窗口的顶部。
它将从 top: 45px
开始并在滚动时停留在 top: 0
。
我的第一个方法是将它设置在 position: fixed; top: 45px
并在 scroll
事件中使用 JS 更改值。但是 Firefox 给了我有关在 this post 上讨论的“异步平移”的警告。 .
我已经能够通过一些 CSS 技巧来做到这一点,但我想知道是否有更简单的 CSS 方法或有效的 JS 方法来做到这一点(不发出警告)。
body {
position: relative;
height: 100%;
width: 100%;
background-color: grey;
overflow-x: hidden;
margin: 0;
}
.container {
position: absolute;
top: 0;
left: -1px;
width: 1px;
bottom: 0;
padding-top: 45px;
overflow: visible;
}
nav {
position: sticky;
top: 0;
transform: translateX(-50%);
margin-left: 50vw;
width: 300px;
height: 70px;
background-color: red;
}
header {
height: 50vh;
background-color: blue;
}
main {
height: 200vh;
width: 100%;
background-color: green;
}
<div class="container">
<nav></nav>
</div>
<header>
</header>
<main>
</main>
最佳答案
您可以简化代码并避免使用额外的容器:
body {
background-color: grey;
margin: 0;
}
nav {
position: sticky;
top: 0;
width: 300px;
height: 70px;
margin:45px auto -115px; /* 115 = height + margin-top */
background-color: red;
}
header {
height: 50vh;
background-color: blue;
}
main {
height: 200vh;
background-color: green;
}
<nav></nav>
<header>
</header>
<main>
</main>
关于javascript - 导航栏 : position Absolute and Sticky,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701287/