DIV CSS 佈局教程網

用 Bootstrap 監聽滾動實現頂部導航吸附
編輯:關於JavaScript     

頁面往下滾動時,讓頂部導航欄吸附在視窗上方,是列表頁和後台管理頁面很常見的需求。用 Bootstrap 的 navbar 配合幾行 jQuery 就能實現。

HTML 結構

關鍵是外層套一個佔位的 wrap,內層放真正要固定的 menu:

<body data-spy="scroll" data-target="#bs-example-navbar-collapse-1">
<div id='menu_wrap'>
  <div class='menu'>
    <nav class="navbar navbar-default" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="#" style="font-weight:bold">植被數據錄入</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
          <button type="button" class="btn btn-primary"
                  style="float: right;margin-right: 10px;margin-top: 5px;"
                  data-dismiss="modal" data-target="#mychart2-zb">
            <span aria-hidden="true">保存</span>
          </button>
          <button type="button" class="btn btn-primary"
                  style="float: right;margin-right: 10px;margin-top: 5px;"
                  data-dismiss="modal" data-target="#mychart2-zb">
            <span aria-hidden="true">取消</span>
          </button>
        </div>
      </div>
    </nav>
  </div>
</div>
</body>

CSS

menuFixed 就是吸附狀態的樣式;#menu_wrap 的高度要等於 navbar 的高度,用來在 menu 變成 fixed 之後頂住原來的位置,避免內容突然上竄:

.menu{
  width:100%;
  z-index:99;
}
.menuFixed{
  position:fixed;
  top:0;
  left:0;
}
#menu_wrap{
  height:50px;
  width:100%;
}

JS 監聽滾動

<script>
$(window).scroll(function () {
  var menu_top = $('#menu_wrap').offset().top;
  if ($(window).scrollTop() >= menu_top) {
    $('.menu').addClass('menuFixed')
  } else {
    $('.menu').removeClass('menuFixed')
  }
});
</script>

引入依賴

<script type="text/javascript" src="../bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>

這個方案的好處是完全不動 DOM 結構,只在滾動到臨界點時切換一個 class。如果頁面裡還有其他固定元素,記得把 z-index 分好層級,別互相遮住。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved