<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>固定导航栏</title>
<style>
*{
margin:0;
padding:0;
}
#one{
background:goldenrod;
height:100px;
width:500px;
font-size:20px;
}
#two{
background:rgb(109, 240, 245);
height:500px;
width:500px;
font-size:20px;
}
#three{
background:rgb(247, 157, 194);
height:500px;
width:500px;
font-size:20px;
}
</style>
</head>
<body>
<div id="one">这是顶部</div>
<div id="two">这是中间</div>
<div id="three">这是尾部</div>
<script>
window.onload = function() {
var one = document.getElementById('one');
var two = document.getElementById('two');
var three = document.getElementById('three');
window.onscroll=function(){
if(document.documentElement.scrollTop >= one.offsetHeight ){
one.style.cssText="position:fixed;top:0px;";
two.style.marginTop = one.offsetHeight+"px";
}else {
one.style.cssText="position:static;";
two.style.marginTop ='0px';
}
}
}
</script>
</body>
</html>