吸顶效果
关键:offsetTop、scrollTop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding:0;
margin:0;
text-align: center;
}
#b_top{
height:200px;
background-color: #127641;
}
#b_center{
height:40px;
background-color: #623423;
}
#b_bottom{
height:1000px;
background-color: #287582;
}
#b_footer{
height:50px;
background:#671244;
}
.active{
top:0;
width:100%;
position: fixed;
z-index: 2;
}
</style>
</head>
<body>
<div id='b_top'>轮播图</div>
<div id='b_center'>导航</div>
<div id='b_bottom'>内容</div>
<div id='b_footer'>底部</div>
<script>
var b_center=document.getElementById('b_center')
//获取导航栏顶部偏移量
var b_top=b_center.offsetTop
//注册滚动事件
document.body.onscroll=()=>{
// 获取滚动偏移量
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop
//判断
if(scrollTop>=b_top){
b_center.className='active'
}else{
b_center.className=''
}
}
</script>
</body>
</html>