Jquery ナビ固定 スクロール

01
02
03
04
05
06
07
08
09
10
11
12
var nav = $('#navbar-scrollspy'),
    offset = nav.offset();
    mT = nav.height();
$(window).scroll(function () {console.log(mT);
  if($(window).scrollTop() > offset.top) {
    nav.addClass('fixed');
    $('#contents').css('marginTop', mT + 20); // 20:navのmargin-bottom
  } else {
    nav.removeClass('fixed');
    $('#contents').css('marginTop', 0);
  }
});
1
2
3
4
5
<div id="navbar-scrollspy">
  <ul>
    <li><a href="#">メニュー</a></li>
  </ul>
</div>
1
2
3
4
5
6
.fixed {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 9999;
}
PAGE TOP