10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

対象要素までヌルッと自動スクロールするメソッドの書き方!

Last updated at Posted at 2019-10-27

まえがき

無限番煎じですが、調べるのに地味に時間がかかったので、自分用を兼ねて残しておきます。

コード

scrollToTarget() {
    const element = document.getElementById("target-id")
    const rect = element.getBoundingClientRect()
    const currentScrolledHeight = window.pageYOffset || document.documentElement.scrollTop
    const position = window.innerHeight * 0.9
    window.scrollTo({top: rect.bottom + currentScrolledHeight - position, behavior: "smooth"})
}

このメソッドが実行された際の動きとしては
idがtarget-idである要素の下部が、ウインドウの上から90%のところに来るようにヌルッとスクロールします。

理屈

  • idがtarget-idである要素の相対座標とサイズを取得する(rect)
  • すでにスクロールされている高さを取得(currentScrolledHeight)
  • ウインドウサイズの上から90%の位置取得(position)
  • target-idである要素の下部の相対座標 + すでにスクロールされている高さ = target-idである要素の下部の絶対座標
  • window.scrollToは、指定座標がウインドウの一番上にくるようにスクロールするため、positionを引いて位置調整する
  • デフォルトだと、一瞬でスクロールするせいで画面がどの位置なのか混乱を招くので、behavior: "smooth"を指定することでスクロールアニメーションでヌルッとさせる

あとがき

scrollToの引数のtopの部分をleftにしたら横スクロールになったり、rect.bottomrect.topにすることでターゲットの上部座標を基準にできたりしますので、都度改造して使ってください!

10
7
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
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?