jquery ページ内リンクへアニメーションで移動

2013年12月8日

ページ内リンクへプラグインを使わずにアニメーションで移動するスムーズスクロールに関するメモ。

animate メソッドと scrollTop プロパティ

参考:「jQueryで画面をスクロールさせる時の注意点

画面をスクロールさせる場合 animate メソッドと scrollTop プロパティを利用するが、どのセレクタに対して実行すべきかはブラウザ(WebKit かそれ以外)により異なる。

WebKit : body 要素
それ以外 : html 要素

  1. $('body').animate({ scrollTop: 0 }); // WebKit
  2. $('html').animate({ scrollTop: 0 }); // WebKit以外

以下のように両方を指定して全てのブラウザに対応することができるが、単純なスクロールだけなら問題はないが、両方指定するとコールバックを指定している場合、コールバックが2回呼ばれてしまう。

  1. $('html, body').animate({ scrollTop: 0 });

そのためブラウザを判定する必要があるが、jQuery 1.9 になって $.browser が使えなくなっているので、「使用したい機能が機能するか」で判定する。

参考:「jQuery 1.9 で $.browser が使えなくなってしまった対策

スクロールさせることができる要素が html か body かを判定するには、実際にどちらの要素でスクロールするかを調べる。

  1. var isHtmlScrollable = (function(){
  2. var html = $('html'), top = html.scrollTop();
  3. var elm = $('<div/>').height(10000).prependTo('body');
  4. html.scrollTop(10000);
  5. var rs = !!html.scrollTop();
  6. html.scrollTop(top);
  7. elm.remove();
  8. return rs;
  9. })();
  10. //スクロールのアニメーション
  11. $(isHtmlScrollable ? 'html' : 'body').animate({scrollTop:100});

以下は全て上記の関数(isHtmlScrollable)の記述を前提。

ページトップへの移動

href 属性の値が「#」の場合、ページトップへアニメーションで移動する。

  1. jQuery(document).ready(function($) {
  2. $('a[href=#]').click(function () {
  3. $(isHtmlScrollable ? 'html' : 'body').animate({
  4. scrollTop: 0
  5. }, 500);
  6. return false;
  7. });
  8. });

注意

但し、href 属性の値が「#」でも、上記のアニメーションを適用したくないものもあるので、それらに関しては not() を使って除外する。例えばこのサイトの場合、ナビゲーションの「その他」は階層メニューになっているので、上記を使用すると階層メニューが機能しなくなるので、以下のようにする。それらがあまりに多い場合は、アニメーションするものには、クラスを付けるなど考える必要があるかもしれない。

  1. jQuery(document).ready(function($) {
  2. $('a[href=#]').not('#header-nav a.dropdown-toggle').click(function () {
  3. $(isHtmlScrollable ? 'html' : 'body').animate({
  4. scrollTop: 0
  5. }, 500);
  6. return false;
  7. });
  8. });

ページ内リンクとページトップへの移動

ある要素の id 属性へのリンクへの移動。<a href=”#someElement” > のような場合にも対応するには以下のようにしてみる。

  • $(“[属性名^=’値’]”):特定の属性が指定した値で始まっている要素
  • .not() 除外する要素を指定(除外するものがなければ不要)
  • 要素の href 属性の値を「hrefval」に格納
  • 「hrefval」はページトップの場合「#」、その他の場合は要素の id「#id名」
  • 対象となる要素「targetelement」を生成
  • 要素のポジションを取得
  • その位置までアニメーション
  1. jQuery(document).ready(function($) {
  2. $('a[href^=#]').not('アニメーションさせない a 要素').click(function(){
  3. var hrefval= $(this).attr('href');
  4. var targetelement = hrefval == "#" ? $('html') : $(hrefval);
  5. var positiontop = targetelement.offset().top;
  6. $(isHtmlScrollable ? 'html' : 'body').animate({
  7. scrollTop: positiontop
  8. }, 500);
  9. return false;
  10. });
  11. });

スクロールすると「先頭へ」というリンクを表示させる

ある程度以上スクロールすると「先頭へ」というリンクを表示させ、クリックするとページ先頭にアニメーションで移動する。

  • フッターなどの要素の後に「先頭へ」というリンク(クラス名:”tothetop”)を追加する
  • リンクを非表示にする topBtn.hide();
  • スクロールの値(以下の例では500px)に応じてリンクをアニメーションで表示・非表示にする
  • その後に前述のアニメーションでの移動に関する記述をする
  1. jQuery(document).ready(function($) {
  2. $('#footer').after('<div class="tothetop"><a href="#">先頭へ</a></div>');
  3. var topBtn = $('.tothetop');
  4. topBtn.hide();
  5. $(window).scroll(function () {
  6. if ($(this).scrollTop() > 500) {
  7. topBtn.fadeIn();
  8. } else {
  9. topBtn.fadeOut();
  10. }
  11. });
  12. //ページ内リンクとページトップへの移動
  13. $('a[href^=#]').not('アニメーションさせない a 要素').click(function(){
  14. var hrefval= $(this).attr('href');
  15. var targetelement = hrefval == "#" ? $('html') : $(hrefval);
  16. var positiontop = targetelement.offset().top;
  17. $(isHtmlScrollable ? 'html' : 'body').animate({
  18. scrollTop: positiontop
  19. }, 500);
  20. return false;
  21. });
  22. });

「ページ先頭へ」というリンクのCSSの例

  1. div.tothetop {
  2. position: fixed;
  3. right: 5%;
  4. bottom: 5%;
  5. z-index: 1500;
  6. }
  7.  
  8. div.tothetop a {
  9. display: block;
  10. font-weight: bold;
  11. color: #FFF;
  12. padding: 10px;
  13. margin: 0;
  14. background-color: #AAA;
  15. font-size: 0.8em;
  16. outline: none;
  17. text-decoration: none;
  18. /* Firefox v1.0+ */
  19. -moz-border-radius:6px ;
  20. /* Safari v3.0+ and by Chrome v0.2+ */
  21. -webkit-border-radius:6px ;
  22. /* Firefox v4.0+ , Safari v5.0+ , Chrome v4.0+ , Opera v10.5+ and by IE v9.0+ */
  23. border-radius:6px ;
  24. }
  25.  
  26. div.tothetop a:hover {
  27. color: #9CF;
  28. background-color: #666;
  29. }

スピードやポジションの調整

以下は移動する距離に応じてスピードを調整(速くなり過ぎないなど)して、ページ内リンクへの移動の場合は、ナビゲーションが常に表示されているため、位置を調整する例。

  1. jQuery(document).ready(function($) {
  2. $('a[href^=#]').not('アニメーションさせない a 要素').click(function(){
  3. var hrefval= $(this).attr('href');
  4. var positiontop;
  5. var speed;
  6. if(hrefval == "#") {
  7. positiontop = 0;
  8. speed = 200 + $(this).offset().top /30;
  9. }else{
  10. var targetelement = $(hrefval);
  11. positiontop = targetelement.offset().top -120;
  12. speed = 200 + (positiontop + 120) / 30;
  13. }
  14. $(isHtmlScrollable ? 'html' : 'body').animate({
  15. scrollTop: positiontop
  16. }, speed);
  17. return false;
  18. });
  19. });

外部ページでもスムーズスクロール

ページ内リンクではなく、外部ページでもスムーズスクロールする方法。

  • ページ内リンクと同様にスクロールさせることができる要素が html か body かを判定
  • # 記号に続くURL の部分(ハッシュ)を「window.location.hash」で取得
  • ハッシュが空文字でなければ、それを元にそのポジションを取得(下記の場合は 100px 上に調整)
  • animate() でアニメーション
  1. var isHtmlScrollable = (function(){
  2. var html = $('html'), top = html.scrollTop();
  3. var elm = $('<div/>').height(10000).prependTo('body');
  4. html.scrollTop(10000);
  5. var rs = !!html.scrollTop();
  6. html.scrollTop(top);
  7. elm.remove();
  8. return rs;
  9. })();
  10.  
  11. var hash = window.location.hash;
  12. if (hash != "") {
  13. var target = $(hash);
  14. var pos = target.offset().top - 100;
  15. $(isHtmlScrollable ? 'html' : 'body').animate({
  16. scrollTop: pos
  17. }, 500, "swing");
  18. }

注意する点としては、ページ内リンクの場合はページが全て読み込まれている(jQuery の処理なども終了している)が、外部ページの場合は記述する位置によっては、他の jQuery の処理などに影響されて期待した位置にスクロールされない可能性がある。その場合は、記述する位置を最後の方に移して見るのも1つの方法。

window.location / MDN