Pie*_*eay 5 html javascript css css-position sticky
我正在尝试制作一个与标题重叠并在滚动时粘在窗口顶部的导航栏。
它将在滚动时开始top: 45px并停留在top: 0。
我的第一个方法是在事件上使用 JS 设置position: fixed; top: 45px并更改值scroll。但 Firefox 给了我关于这篇文章中讨论的“异步平移”的警告。
我已经能够通过一些 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;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<nav></nav>
</div>
<header>
</header>
<main>
</main>Run Code Online (Sandbox Code Playgroud)
您可以简化代码并避免使用额外的容器:
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;
}Run Code Online (Sandbox Code Playgroud)
<nav></nav>
<header>
</header>
<main>
</main>Run Code Online (Sandbox Code Playgroud)