LoginSignup
1
0

More than 5 years have passed since last update.

javascriptでのページ内smooth scroll

Last updated at Posted at 2016-02-13

以前どっかにあるライブラリ使っていたんですが、エラーが発生したので自分で書きました。
6行目でhtmlとbodyを両方指定しているところがミソです。

/**
 * ページ内リンクでスムーズなリンク移動
 * @param {object} obj -クリックされたオブジェクト
 */
function smoothScroll(obj){
    var speed = 1000;
    var href= obj.attr("href");
    var target = $(href == "#" || href == "" ? 'html' : href);
    var position = target.offset().top;
    $("html, body").animate({scrollTop:position}, speed, "swing");
    return;
}

用意したらクリックで発動!
speedを変えれば移動速度を変更できます。

$(document).on('click','a[href^=#]',function(){
    smoothScroll($(this));
});
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0