Skip to content

Instantly share code, notes, and snippets.

@k-ish
Last active October 9, 2018 06:13
Show Gist options
  • Save k-ish/172e71d4187375ec5c9547478b18a52f to your computer and use it in GitHub Desktop.
Save k-ish/172e71d4187375ec5c9547478b18a52f to your computer and use it in GitHub Desktop.
scroll highlight
<!-- スクロール位置によって、ハイライトする項目が変化 -->
<header>
<h1>Highlight Menu</h1>
<nav>
<ul>
<li class="current"><a href="#">Section1</a></li>
<li><a href="#">Section2</a></li>
<li><a href="#">Section3</a></li>
<li><a href="#">Section4</a></li>
</ul>
</nav>
</header>
<h1>Section1</h1>
<h1>Section2</h1>
<h1>Section3</h1>
$(function(){
// ブラウザをスクロール
$(window).scroll(function(){
// 各コンテンツ位置とスクロール量の関係を調べる
for(var i = 1; i <= 4; i++){
if($("section:nth-child(" + i + ")").offset().top < $(window).scrollTop() + 300){
// 現在のcurrentクラスを削除
$("nav li").removeClass("current");
// 新しくcurrentクラスを追加
$("nav li:nth-child(" + i + ")").addClass("current");
}
}
});
});
/* .current 変化時のスタイルを記述 */
.current {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment