0
1

はじめに

特定の要素までスクロールするための実装方法として、scrollIntoView() メソッド があります。
本記事ではボタンが押下されたことをトリガーとし、scrollIntoViewを使って任意の位置までの滑らかな縦スクロールを実装します。

behavior: 'smooth'

behavior: 'smooth' を指定すると任意の要素までの滑らかなスクロールを実装できます。

ブラウザの互換性

instant、autoは瞬時に任意の位置に移動。

blockオプション

  • nearest:最も近い位置までスクロール(start or end が適用)
  • start:要素の上端がビューポートの上端に合うようにスクロール
  • center:要素がビューポートの中央に位置するようにスクロール
  • end:要素の下端がビューポートの下端に合うようにスクロール

動かしてみる

文字だけだとイメージがつきにくいので実際に動かしてみます。

See the Pen scrollViewSample by enumura (@enumura) on CodePen.

ソース

index.html
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>scrollIntoView デモ</title>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <div class="button-container">
        <button id="scrollButton1">Scroll:Auto+Nearest</button>
        <button id="scrollButton2">Scroll:Smooth+Start</button>
        <button id="scrollButton3">Scroll:Smooth+Center</button>
        <button id="scrollButton4">Scroll:Smooth+End</button>
    </div>
    <div class="content">
        <div id="targetElement" class="target">スロール先のターゲット</div>
    </div>
    <script src="script.js"></script>
</body>
</html>
index.css
index.css
body {
  background-color: lightblue;
}
.content {
  height: 1500px;
  padding-top: 50px;
}
.target {
  text-align: center;
  margin-top: 1000px;
  padding: 20px;
  background-color: lightcoral;
}
button {
  width: 70%;
  padding: 10px 20px;
  margin: 5px;
}
.button-container {
  position: fixed;
  flex-wrap: wrap;
  top: 10px;
  left: 10px;
  display: flex;
  gap: 10px;
}
scripts.js
scripts.js
// ボタンとターゲット要素を取得
const button1 = document.getElementById('scrollButton1');
const button2 = document.getElementById('scrollButton2');
const button3 = document.getElementById('scrollButton3');
const button4 = document.getElementById('scrollButton4');
const targetElement = document.getElementById('targetElement');

// ボタン1:スムーズにスクロールし、ターゲット要素が最も近い位置に表示
button1.addEventListener('click', function() {
    targetElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
});

// ボタン2:スムーズに上部までスクロール
button2.addEventListener('click', function() {
    targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
});

// ボタン3:スムーズに中央までスクロール
button3.addEventListener('click', function() {
    targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
});

// ボタン4:スムーズに下部までスクロール
button4.addEventListener('click', function() {
    targetElement.scrollIntoView({ behavior: 'smooth', block: 'end' });
});

参考

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