zoukankan      html  css  js  c++  java
  • 下滚导航条自动隐藏,上滚显示

    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>
  • 相关阅读:
    如何使用RabbitMQ实现事件总线
    一起学Vue:UI框架(elementui)
    一起学Vue:访问API(axios)
    一起学Vue:CRUD(增删改查)
    一起学Vue:路由(vuerouter)
    如何使用IMemoryCache实现内存缓存
    手把手教你AspNetCore WebApi:Nginx(负载均衡)
    一起学Vue:状态管理(Vuex)
    自我介绍
    牛客练习赛74AB
  • 原文地址:https://www.cnblogs.com/seeding/p/11856866.html
Copyright © 2011-2022 走看看