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

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


Warning: include(/home/youhei0828/kachibito.net/public_html/wp-content/themes/cocoon-master/my-php/jquery-other-snippets.php): Failed to open stream: No such file or directory in /home/youhei0828/kachibito.net/public_html/wp-content/themes/kachibito7_with_cocoon_child/functions-module/shortcode/add-post-myphp.php on line 7

Warning: include(): Failed opening '/home/youhei0828/kachibito.net/public_html/wp-content/themes/cocoon-master/my-php/jquery-other-snippets.php' for inclusion (include_path='.:/opt/php-8.1.29/data/pear') in /home/youhei0828/kachibito.net/public_html/wp-content/themes/kachibito7_with_cocoon_child/functions-module/shortcode/add-post-myphp.php on line 7