根據瀏覽器的滑動條 固定導航欄

固定導航欄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 }
相關文章
相關標籤/搜索