滚动条向下到一定程度菜单栏就固定到顶部,滚动条回到顶部菜单栏恢复
<html> <head> <meta charset="utf-8"> <title>滚动固定</title> <style type="text/css"> *{ margin:0 auto; padding:0;} #header{ width:100%; height:200px;} #nav{ width:100%; height:50px; background-color:#00F; top:0px;} .content{ width:800px; height:300px; background-color:#0FF; margin-top:20px} </style> </head> <body> <div id="header"></div> <div id="nav"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> </body> </html> <script type="text/javascript"> var nav = document.getElementById("nav"); /* 监听滚动,垂直方向大于200就锁定顶部,小于200就解锁 */ window.onscroll = function() { if(window.scrollY>=200) { nav.style.position = "fixed"; } else { nav.style.position = ""; } } </script>
初始
向下移动
回到顶部