根据浏览器的滑动条 固定导航栏

固定导航栏

前言:很多网站都有这种网页的效果:滑动浏览器右侧的滚动条,导航栏会一直处于最上方

下面我就来简单实现以下这个功能


 

 一.首先我们来写一下html的结构:

1 <div class="top" id="top"></div>
2 <div class="nav" id="nav"></div>
3 <div class="main" id="main"></div>

  二.我们来简单写一下样式

   这个结构可以说是简单明了,由三部分组成  顶部  导航栏 还有主体部分

  但是我们并不打算继续写下去  我们简单的用样式表达一下  用颜色划分区域 这个是练习的好方法

   

 1 <style>
 2         .top {
 3             height: 200px;
 4             width: 100%;
 5             background-color: #f00;
 6         }
 7         .nav {
 8             height: 150px;
 9             background-color: skyblue;
10             width: 100%;
11         }
12         .main {
13             margin-top: 100px;
14             height: 1000px;
15             width: 100%;
16             background-color: black;
17         }
18     </style>

    三.接着我们来写一下js的代码

    

 1 window.onscroll = function () {
 2         if (getScroll().top >= my$("top").offsetHeight){
         //利用定位使其固定 脱标
3 my$("nav").style.position = "fixed"; 4 my$("nav").style.top = 0;
         //设置main 的 margintop 防止由于nav的脱标 main 整体向上移动 而造成下拉过程并不流畅的效果
5 my$("main").style.marginTop = (my$("nav").offsetHeight + 100) + "px"; 6 } 7 else {
          //取消设置的东西 然后恢复成原来的样子
8 my$("nav").style.position = ""; 9 my$("main").style.marginTop = "100px"; 10 } 11 }

 

posted @ 2019-01-11 22:35  Lzxgg  阅读(599)  评论(0编辑  收藏  举报