ページ内ナビゲーションでスムーズスクロールしてページの上部にフィックスしてついてくるというのはよくあると思います。で、下向きの矢印がついてるとスムーズスクロールだとすぐにわかると思うんですけど、フィックスしてついてくるとき、通り過ぎた要素のナビも下を向いてると違和感を感じますよね?
ということで、通り過ぎた要素のナビの矢印が上を向くフィックスナビを考えてみました。
以下はコードです。CSSは見た目の調整にのみ使っているので、省略しています。
矢印はFont Awesomeで入れているので、コピペするときはお忘れなく。
背景画像の切り替えにする場合は、.attr(‘class’,’fa fa-caret-up’)を.css(‘background-image’,’画像パス’);にすればできます。セレクタをお間違えないように。
HTML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- aタグのhrefの値とsectionのid名は合わせておく必要があります。 --> | |
<nav> | |
<ul> | |
<li><a href="#sec1">sec1<i class="fa fa-caret-down"></i></a></li> | |
<li><a href="#sec2">sec2<i class="fa fa-caret-down"></i></a></li> | |
<li><a href="#sec3">sec3<i class="fa fa-caret-down"></i></a></li> | |
<li><a href="#sec4">sec4<i class="fa fa-caret-down"></i></a></li> | |
<li><a href="#sec5">sec5<i class="fa fa-caret-down"></i></a></li> | |
<li><a href="#sec6">sec6<i class="fa fa-caret-down"></i></a></li> | |
</ul> | |
</nav> | |
<section id="sec1">sec1</section> | |
<section id="sec2">sec2</section> | |
<section id="sec3">sec3</section> | |
<section id="sec4">sec4</section> | |
<section id="sec5">sec5</section> | |
<section id="sec6">sec6</section> | |
<footer></footer> |
jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('nav a[href^="#"]').on('click',function(){ | |
var scrId= $(this).attr('href');//クリックしたaタグのhrefを取得 | |
var targetPos = $('section' + scrId).offset().top - 100;//同じid名を持つsectionの位置を取得 | |
$('html,body').animate({scrollTop:targetPos});//そのsectionの位置までスクロールする | |
return false; | |
}); | |
$(window).scroll(function(){ | |
for(i=1;i<7;i++){//要素の数だけ繰り返し | |
secArrow(i); | |
} | |
}); | |
function secArrow(id){ | |
var secPos = $('section#sec' + id).offset().top + 100;//矢印が反転するときの要素の位置取得 | |
var scrTop = $(window).scrollTop();//スクロール量取得 | |
if(scrTop > secPos){ | |
$('a[href="#sec'+ id +'"]').children('i').attr('class','fa fa-caret-up'); | |
} else{ | |
$('a[href="#sec'+ id +'"]').children('i').attr('class','fa fa-caret-down'); | |
} | |
} |