0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Web】特定の要素へスクロールさせる方法まとめ

Posted at

はじめに

今年に入ってWebの開発を進めています。
その際、画面を特定の要素までスクロールさせるために少々調べたので、今回は備忘録的に実装方法をまとめておこうと思います。

実装方法

まず、実装の全体像は以下になります。

page.tsx
import { useRef } from "react";

export default function Page() {
  const testRefs = useRef<(HTMLDivElement | null)[]>([]); 

  const testList = [
    { id: 1, value: "テストテスト" },
    { id: 2, value: "テストテスト" },
    { id: 3, value: "テストテスト" },
  ]; 

  const handleSelectItem = (index: number) => {
    if (skillRefs.current[index]) {
      skillRefs.current[index]?.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  };

  return (
    <div>
      {testList.map((item, index) => (
        <div key={item.id} ref={(el) => { testRefs.current[index] = el; }}>
          <TestComponent 
              item={item} 
              onSelectItem={(index) => handleSelectItem(index)
          />
        </div>
      ))}
    </div>
  );
}

実装の全体像としては以上です。
重要なのは主に2つになります。

  1. useRef を使って各 TestComponent の要素を配列で管理
  2. scrollIntoView関数を使用し、受け取ったindexに該当する要素へスクロール

たったこれだけでWebでは綺麗にスクロールしてくれます、非常に簡単で便利ですね。

ちなみにscrollIntoView関数に渡すbehaviorとblockには他にも以下値を設定可能です。

behavior(スクロールの動き)

動作 特徴
auto デフォルトのスクロール動作 ブラウザの標準動作(通常 instant
smooth スムーズスクロール なめらかにスクロールする
instant 一瞬でスクロール(瞬間移動) 瞬時に目的の位置へスクロール(アニメーションなし)

block(要素の表示位置)

動作 スクロール後の表示位置
start 要素の先頭をスクロール先に 画面の一番上 に要素が来る
center 要素を中央に配置 画面の中央 に要素が来る
end 要素の末尾をスクロール先に 画面の下部 に要素が来る
nearest 近い位置へスクロール 現在のスクロール位置から最小の移動量 で調整

以上になります。
オートスクロール実装時の参考にしてもらえればと思います。

さいごに

順調に減量中です、引き続き健康管理に気合いを入れつつWebの実装も進めていきます!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?