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

固定导航栏html

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

下面我就来简单实现如下这个功能网站


 

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

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

  二.咱们来简单写一下样式code

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

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

   

 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的代码get

    

 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 }
相关文章
相关标签/搜索