如何让 #headnav
在页面滚动位置到达顶部时粘在顶部,然后在返回到原始位置时松开?
附言代码中重复的“CONTENT”是为了模拟滚动。这不是垃圾邮件
<h1>I AM A HEADER</h1>
<div id="headnav"></div>
<pre><h1>
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
CONTENT
</h1></pre>
body {
margin:0
}
#headnav {
height: 75px;
width: 100%;
background-color: black;
}
最佳答案
这是一件非常简单的事情。
找出 header 的原始位置,然后将滚动处理程序附加到主体,以根据 div 的原始位置检查滚动位置。
- 如果滚动位置大于原来的位置,添加
position: fixed
- 如果滚动位置小于原来的位置,去掉
position: fixed
( Demo )
var headnav = document.getElementById('headnav');
var headnavPos = headnav.offsetTop;
window.onscroll = function() {
if(document.body.scrollTop > headnavPos) {
if(headnav.style.position !== 'fixed') {
headnav.style.position = 'fixed';
}
} else {
if(headnav.style.position === 'fixed') {
headnav.style.position = '';
}
}
}
关于javascript - 如何使div到达窗口顶部时保持在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31082250/