JavaScript-滚动固定导航

Posted on 2017-12-08 17:12  神笔码农  阅读(168)  评论(0编辑  收藏  举报
<style type="text/css">
*{ margin:0px auto; padding:0px}
#top{ width:100%; height:200px; background-color:blue}
#menu{ width:100%; height:100px; background-color:red}
.item{ width:200px; height:500px; background-color:#33F; margin-top:10px}
</style>
</head>

<body>
    <div id="top"></div>
    <div id="menu"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>    
    <div class="item"></div>
    
      
</body>
<script type="text/javascript">
    //定义滚动条事件:当滚动条向下滚动超过“top”时,“menu”的position属性变为fixed
    window.onscroll = function(){   
        var menu = document.getElementById("menu");
        if(window.scrollY>=200){
            menu.style.position = "fixed";
            menu.style.top = "0px";    
        }else{
            //当滚动条滚动不超过200时,取消fixed效果
            menu.style.position = " ";    
        }
    }
</script>