前回記事CSSでメニューなどのスクロールしたらついてくるエリアを作る1では一番上にある部分をスクロールしてもついてくる状態にしました。 今度は途中にあるメニュー部分などをスクロールしてもついてくる方法について考えていきたいと思います。12月3日記事

イメージ
スクロールする前

スクロールしてnav部分をすぎると?
こんな感じでナビ部分だけが残る

目次





コード

HTML

<!DOCTYPE HTML>
<html>

<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="reset.css">
	<link rel="stylesheet" type="text/css" href="style.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
	<script>
		$(function() {
			var nav_height = $('nav').offset().top;

			$(window).on('scroll load', function() {
				var now_height = $(window).scrollTop();

				if (now_height >= nav_height) {
					$('nav').css('position', 'fixed');
				} else {
					$('nav').css('position', 'inherit');
				}
			});
		});

	</script>
	<title>途中にあるメニューがスクロールしてもついてくる</title>
</head>

<body>
	<header>
	</header>
	<nav>
		<p>ここにリストタグなどを使ってメニューを作る</p>
	</nav>
	<div id="wrapper">
		<div class="contents">
		</div>
		<div class="contents">
		</div>
		<div class="contents">
		</div>
	</div>
</body>

</html>

CSS

@charset "utf-8";
/* CSS Document */

header {
	width: 100%;
	height: 200px;
	background: #FFC;
}
nav {
	width: 100%;
	height: 50px;
	background: #FCF;
	top: 0;
	left: 0;
	position: inherit;
}
.contents {
	width: 100%;
	height: 400px;
	background: #CFF;
	margin-bottom: 30px;
}



まとめ

navにはfixedした際にその基準となるtopやleftを記述しておくことが重要です。その部分を記載してスクロールした際にも使えるようにしておきましょう。

以上

最終更新:2015年12月04日 12:05
添付ファイル