LoginSignup
184
178

More than 5 years have passed since last update.

たった1行!jQueryで指定箇所までアニメーションつきで自動スクロールさせる方法

Last updated at Posted at 2014-12-15

 jQueryで指定したセレクタの箇所まで自動でスクロールする方法を紹介します。

次のように1行で書くことができます。

sample.js
$("html,body").animate({scrollTop:$('セレクタ').offset().top});

たとえばheaderのidをheaderとしたならば

sample.js
$("html,body").animate({scrollTop:$('#header').offset().top});

を呼んであげるだけでheaderまで自動でスクロールしてくれます。

この1行を少し分割して説明します。

$('セレクタ')
  • 指定したセレクタのオブジェクトが得られます。
.offset()
  • ドキュメント上での表示位置を取得します。簡単にいうとウィンドウの左上を基準とした位置が得られます。
.top
  • .offset()にはtopとleftが入っています。

ここまでで、

$('セレクタ').offset().top

で指定したセレクタの上からの位置が数字で取得できます。

  • 最後に。
$("html,body").animate({scrollTop:数字});

で数字の位置までアニメーションをしながら自動でスクロールします。
数字が0ならば一番上まで戻る、ということもできます。

184
178
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
184
178