固定导航栏、吸顶效果

时间:2022-12-06 23:20:36
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{margin:0;padding:0}
img{
vertical-align: top;
}
        .top img{
            height:168px;
        }
.main{
margin:0 auto;
width:1000px;
margin-top:10px;

}
        
</style>
</head>
<body>
    <div class="top" id="top">
     <img src="images/top.png" alt=""/>
    </div>
    <div class="nav" id="Q-nav">
     <img src="images/nav.png" alt=""/>
    </div>
    <div class="main">
     <img src="images/main.png" alt=""/>
    </div>
</body>
</html>
<script type="text/javascript">
    //当触发滚动条时,获取页面滚走的距离
    //如果页面滚走的距离 大于 头部高度时,开始 吸顶(固定定位)
    
    var h = 168;
    var nav = document.querySelector("#Q-nav");
    window.onscroll = function(){
        //获取页面滚走距离
        var sTop = document.documentElement.scrollTop || document.body.scrollTop;
        if( sTop > h ){
            nav.style.position = "fixed";
            nav.style.top = 0;
        }else{
            nav.style.position = "static";
        }
    }
</script>