第一种原生js写法
<style>
* {
margin: 0;
padding: 0;
}
</style>
<div>
<div style="height: 100px;"></div>
<div id="nav" style="background: red;height: 30px;box-sizing: border-box; top:0;z-index:9999;width: 100%;"> </div>
<div style="background: skyblue;height: 500px;box-sizing: border-box;"></div>
<div style="background: yellowgreen;height: 800px;box-sizing: border-box;"></div>
</div>
<script>
let mynav = document.getElementById('nav')
window.onscroll = () => {
if (document.documentElement.scrollTop > mynav.offsetTop) {
mynav.style.position = "fixed";
} else {
mynav.style.position = "static";
}
};
</script>
第二种css简单写法(浏览器兼容)
<style>
* {
margin: 0;
padding: 0;
}
#nav {
position: -webkit-sticky;
position: sticky;
top: 0;
}
</style>
<div>
<div style="height: 100px;"></div>
<div id="nav" style="background: red;height: 30px;box-sizing: border-box; top:0;z-index:9999;width: 100%;"> </div>
<div style="background: skyblue;height: 500px;box-sizing: border-box;"></div>
<div style="background: yellowgreen;height: 800px;box-sizing: border-box;"></div>
</div>
效果如下:
初始页面(滚动条在最上方):
滚动条移动在中间,此时导航栏已经吸顶:
滚动条在最底部,导航栏吸顶: