ページを下にスクロールすると隠れ、上にスクロールするとスィーっと現れるヘッダーを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; //今のポジション値が、一つ前のポジション値となる。
});
});