<!DOCTYPE html>
<html lang="en">
<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>
* {
margin: 0;
padding: 0;
}
header {
line-height: 150px;
text-align: center;
height: 150px;
background-color: greenyellow;
}
nav {
width: 100%;
line-height: 50px;
text-align: center;
height: 50px;
background-color: deepskyblue;
transition: 2s;
}
.sty {
background: rgba(255, 255, 255, .6);
position: fixed;
top: 0;
left: 0;
}
section {
line-height: 1500px;
font-size: 80px;
height: 1500px;
text-align: center;
background-color: #ccc;
}
footer {
line-height: 300px;
text-align: center;
height: 300px;
background-color: red;
}
</style>
</head>
<body>
<header>这是头部</header>
<nav>这是导航栏</nav>
<section>这是内容区</section>
<footer>这是尾部</footer>
<script>
var nav = document.querySelector("nav");
window.onscroll = function () {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop >= 300) {
nav.className = "sty";
} else {
nav.className = "";
}
}
</script>
</body>
</html>
效果图