LoginSignup
21
22

More than 5 years have passed since last update.

下にスクロールすると消えて、上にスクロールすると表示されるメニューをつくる方法

Last updated at Posted at 2016-07-05

サンプル

See the Pen ScrollingMenu(height) by DesignChips (@DesignChips) on CodePen.

See the Pen ScrollingMenu(outerHeight) by DesignChips (@DesignChips) on CodePen.

コード

<body>
  <nav class="menu-wrap">
  <ul class="menu">
    <li><a href="#">menu1</a></li>
    <li><a href="#">menu2</a></li>
    <li><a href="#">menu3</a></li>
    <li><a href="#">menu4</a></li>
    <li><a href="#">menu5</a></li>
  </ul>
</nav>
    <img src="http://lorempixel.com/image_output/nature-q-c-1920-1280-2.jpg" alt="" />
</body>
.menu-wrap {
  padding: 10px 0;
  position: fixed;
  z-index: 9999;
  top: 0;
  left: 0;
  width: 100%;
  background: rgba(0,0,0,.5);
  transition: .3s;
  opacity: 0.8;
}
.menu {
  list-style-type: none;
  width: 960px;
  margin: 0px auto;
  padding: 0;
}
.menu li {
  width: 20%;
  float: left;
  margin: 0;
  padding: 0;
  text-align: center;
}
.menu li a {
  display: block;
  width : 100%;
  padding: 20px 0;
  color: #fff;
  font-size: 14px;
  line-height: 1;
  text-decoration: none;
  transition: .3s;
}
.menu li a:hover {  background: rgba(0,0,0,.3) }

img {
  width: 100%;
}

heught.js

var menuHeight = $(".menu-wrap").height();
var startPos = 0;
$(window).scroll(function(){
  var currentPos = $(this).scrollTop();
  if (currentPos > startPos) {
    if($(window).scrollTop() >= 200) {
      $(".menu-wrap").css("top", "-" + menuHeight + "px");
    }
  } else {
    $(".menu-wrap").css("top", 0 + "px");
  }
  startPos = currentPos;
});

outerHeight.js

// var menuHeight = $(".menu-wrap").height();
var menuHeight = $("#menu-wrap").outerHeight();
var startPos = 0;
$(window).scroll(function(){
  var currentPos = $(this).scrollTop();
  if (currentPos > startPos) {
    if($(window).scrollTop() >= 200) {
      $(".menu-wrap").css("top", "-" + menuHeight + "px");
    }
  } else {
    $(".menu-wrap").css("top", 0 + "px");
  }
  startPos = currentPos;
});

jQuery の height と outerHeight の違い

それぞれ取得できる高さが異なるので注意です。.menu-wrapにpaddingを設定している場合、height()ではメニューが途中までしか隠れず、下の方が表示されてしまいます。

var $('.menu-wrap').height(); // padding, marginを含まない高さ
var $('.menu-wrap').outerHeight(); // paddingを含む高さ
var $('.menu-wrap').outerHeight({margin: true}); // padding, marginを含む高さ
21
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
22