【簡単解説】JavaScriptでスムーズスクロール!scrollIntoViewの使い方
Webサイトの操作性向上には、スムーズなスクロールが欠かせません。
scrollIntoView() を使えば、指定した要素へ滑らかにスクロールさせることが可能です。
ただし、element.scrollIntoView(true) や element.scrollIntoView(false) を使った場合、スムーズなスクロールは実現できません。
本記事では、scrollIntoView() のオプション指定方法や活用方法を実例付きで解説します。
element.scrollIntoView( {
behavior :'値',
block :'値',
inline :'値'
} );
- behavior :'値'
-
スクロール方法を指定します。
- 'smooth' を指定すると滑らかにアニメーションしてスクロールします
- 'instant' を指定するとアニメーションせず即時にスクロールします
- block :'値'
-
スクロール後の要素の垂直配置を指定します。
- 'start' を指定すると要素の上端をスクロール可能な範囲の上端に揃えてスクロールを完了します
- 'center' を指定すると要素の中央をスクロール可能な範囲の中央に揃えてスクロールを完了します
- 'end' を指定すると要素の下端をスクロール可能な範囲の下端に揃えてスクロールを完了します
- 'nearest' を指定すると要素を垂直方向の最も近い端(上端又は下端)に表示される位置でスクロールを完了します(規定値)
- inline :'値'
-
スクロール後の要素の水平配置を指定します。
- 'start' を指定すると要素の左端をスクロール可能な範囲の左端に揃えてスクロールを完了します
- 'center' を指定すると要素の水平中央をスクロール可能な範囲の水平中央に揃えてスクロールを完了します
- 'end' を指定すると要素の右端をスクロール可能な範囲の右端に揃えてスクロールを完了します
- 'nearest' を指定すると要素を水平方向の最も近い端(左端又は右端)に表示される位置でスクロールを完了します(規定値)
サンプルソースコード
左上端
右上端
中央
左下端
右下端
<p class="normal">
<input type="button" id="btn_cm_ss" value="中央(block:start, inline:start)">
<input type="button" id="btn_cm_se" value="中央(block:start, inline:end)"><br>
<input type="button" id="btn_cm_cc" value="中央(block:center, inline:center)"><br>
<input type="button" id="btn_cm_es" value="中央(block:end, inline:start)">
<input type="button" id="btn_cm_ee" value="中央(block:end, inline:end)">
</p>
<div style="width:96%;height:300px;overflow:auto;border:2px solid #666;">
<div style="width:2000px;height:1000px;position:relative;">
<p id="lu" style="position:absolute;left: 5%;top: 5%;">左上端</p>
<p id="ru" style="position:absolute;left:90%;top: 5%;">右上端</p>
<p id="cm" style="position:absolute;left:50%;top:50%;">中央</p>
<p id="lb" style="position:absolute;left: 5%;top:90%;">左下端</p>
<p id="rb" style="position:absolute;left:90%;top:90%;">右下端</p>
</div>
</div>
<script>
document.querySelector("#btn_cm_ss").addEventListener("click",function(){
document.querySelector("#cm").scrollIntoView({behavior :'smooth', block:'start', inline:'start'});
});
document.querySelector("#btn_cm_es").addEventListener("click",function(){
document.querySelector("#cm").scrollIntoView({behavior :'smooth', block:'end', inline:'start'});
});
document.querySelector("#btn_cm_cc").addEventListener("click",function(){
document.querySelector("#cm").scrollIntoView({behavior :'smooth', block:'center', inline:'center'});
});
document.querySelector("#btn_cm_se").addEventListener("click",function(){
document.querySelector("#cm").scrollIntoView({behavior :'smooth', block:'start', inline:'end'});
});
document.querySelector("#btn_cm_ee").addEventListener("click",function(){
document.querySelector("#cm").scrollIntoView({behavior :'smooth', block:'end', inline:'end'});
});
</script>
<input type="button" value="このページ内の上部へスクロール" onclick="document.querySelector('#top').scrollIntoView({behavior :'smooth', block:'start', inline:'start'});">
