<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>吸顶</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#nav{
position: fixed;
left: 0;
top: -50px;
width: 100%;
height: 50px;
background: aquamarine;
box-shadow: 0 0 8px #eee;
transition: all .4s;
}
#nav.show{
top:0;
}
</style>
</head>
<body style="height:2000px;">
<div id="nav"></div>
<script>
window.onload = function () {
var nav = document.getElementById('nav');
window.onscroll = function () {
var top = document.documentElement.scrollTop || document.body.scrollTop;
if(top >= 400){
nav.classList.add('show');
}else {
nav.classList.remove('show');
}
};
};
</script>
</body>
</html>
当滚动条距离顶部400像素的时候,会出现吸顶效果,小于400像素的时候,吸顶效果消失。