<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
.header {
height: 100px;
background-color: red;
}
.nav {
height: 80px;
background-color: skyblue;
100%;
}
.navTwo {
position: fixed;
top: 0;
left: 0;
}
.section {
background-color: pink;
height: 1000px;
80%;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="header"></div>
<div class="nav" id="nav"></div>
<div class="section"></div>
</body>
<script>
window.onload = function() {
//1.获取导航栏距离头部的距离
let navTop = nav.offsetTop
// 2. 监听窗口滚动
window.onscroll = function() {
// 2.1获取实时滚动
let scroll = document.documentElement.scrollTop
if(scroll >= navTop) {
nav.className = 'nav navTwo'
}else {
nav.className = 'nav'
}
}
}
</script>
</html>