LoginSignup
1
3

More than 3 years have passed since last update.

【jQuery】スクロールに合わせてヘッダーを出現・格納させる

Posted at

ページを下にスクロールすると隠れ、上にスクロールするとスィーっと現れるヘッダーをjQueryで実装する。

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <!--jQueryを読み込んでおく-->
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="main.js"></script>
    <title>タイトル</title>
  </head>
  <body>
    <header>
      ここがヘッダーです。
    </header>
  </body>
</html>
style.css
body{
  background: #FFF;
  height:2000px;
}
header{
  background: #000;
  width: 100%;
  height: 100px;
  position: fixed;
  top: 0;
  left: 0;
  transition: .5s; /*ヘッダーが0.5秒かけて動く*/
}
.hide{
  transform: translateY(-100%); /*マイナス方向(上方向)に元の高さ(100px)の100%分移動する*/
}
main.js
$(function(){
  var nowPos = 0;  //現在のスクロールポジション
  var lastPos = 0; //一つ前のスクロールポジション
  $(window).on('scroll',function(){
    nowPos = $(this).scrollTop();
    if (nowPos > lastPos) {
      if (nowPos > 400) {
        $('header').addClass('hide'); //headerタグにhideクラスを付与する
      }
    }else {
      $('header').removeClass('hide'); //headerタグからhideクラスを取り除く
    }
  lastPos = nowPos; //今のポジション値が、一つ前のポジション値となる。
  });
});

1
3
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
1
3