#を使ったページ内リンクをスムーススクロール出来るようにする

Ads

Result

jQuery

$(document).ready(function() {
  function f(string) {
   //正規表現で文字列置換
    return string
      .replace(/^\//,'')  
      .replace(/(index|default).[a-zA-Z]{3,4}$/,'')  
      .replace(/\/$/,'');
  }
  //ハッシュリンクの内容をチェックする
  $('a[href*=#]').each(function() {
    if ( f(location.pathname) == f(this.pathname)
    && location.hostname == this.hostname
    && this.hash.replace(/#/,'') ) {
      //名前付きアンカーをチェックする
      var $td = $(this.hash), $ta = $('[name=' + this.hash.slice(1) +']');
      var $t = $td.length ? $td : $ta.length ? $ta : false;
       if ($t) {
         var off = $t.offset().top;
         //クリックイベント発火
         $(this).click(function() {
           $('html, body').animate({scrollTop: off}, 400);
           return false;
         });
      }
    }
  });
});

css

a{display:block;margin-top:2000px;}

html

<p id="top">top</p>
<a href="#top">go!</a>

via

Improved Animated Scrolling Script for Same-Page Links

タイトルとURLをコピーしました