HTML代码(body内)
<div class="top" id="top"></div> <div class="nav" id="nav"></div> <div class="main-body" id="menu"> <img src="images/img1.jpg" alt=""> <--随便一张img1.jpg--> </div> <div class="footer"></div>
CSS样式
body{ background: pink; margin:0px; padding:0px; } .top{ width:100%; height:80px; background:#ccc; } .nav{ width:100%; height:40px; background:cornflowerblue; } .main-body{ height:1600px; } .footer{ width:100%; height:120px; background:pink; } .navfix{ position:fixed; top:0px; }
JavaScript代码
<script type="text/javascript"> /*页面滚动事件*/ window.onscroll = function () { if(document.documentElement.scrollTop >= document.getElementById('top').offsetHeight ){ document.getElementById('nav').className = 'nav navfix' document.getElementById('menu').style.marginTop="40px" }else{ document.getElementById('nav').className = 'nav' document.getElementById('menu').style.marginTop="0px" } } //============================================== //document.documentElement.scrollTop 滚动条移动的距离 //document.getElementById('top').offsetHeight 导航上面top的高度。offsetHeight获取,知道固定高度的可以直接用数值代替 //document.getElementById('nav').className = 'nav navfix' .className= ,给选定的元素添加css样式 //document.getElementById('nav').className = 'nav' //document.getElementById('main-body').style.marginTop="40px" 40为nav的高度,为了解决bug,也可以设置为 //其中.nav{ 100%; height:40px; background:blue;} //.navifx{ position:fixed; top:0px; } </script>