スムーズスクロールする
- カテゴリ:
- JavaScript
- CSS
- コメント数:
- Comments: 0
◆ scrollTo, scrollBy の引数にオブジェクトを使う
◆ top: 100 などのスクロール量と一緒に behavior: "smooth" を指定する
◆ CSS で scroll-behavior: smooth を指定すると JavaScript では指定しなくてもスムーズにスクロールできる
◆ top: 100 などのスクロール量と一緒に behavior: "smooth" を指定する
◆ CSS で scroll-behavior: smooth を指定すると JavaScript では指定しなくてもスムーズにスクロールできる
JavaScript で
ページ全体のスクロールをするには html タグ (documentElement) か window の scrollTo や scrollBy メソッドを使いますdocument.documentElement.scrollTo({top: 1000})
window.scrollBy({top: 100, left: 100})
などですTo は絶対位置 By は相対位置指定です
ここまでは昔からある機能です
smooth scroll するには 「behavior: "smooth"」 を追加します
window.scrollTo({top: 1000, behavior: "smooth"})
css で overflow: auto などでスクロールバーを出している要素にも使えます
<style>
section{
height: 200px;
overflow: auto;
}
li{
height: 50px;
}
</style>
<section>
<h1>title</h1>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>...</li>
</ul>
</section>
document.querySelector("section").scrollTo({top: 200, behavior: "scroll"})
MDN のマニュアルだと今のところ x, y を指定する方法のみでオブジェクトを渡す方法は載ってませんが csswg の working draft ではちゃんと載ってます
https://www.w3.org/TR/2016/WD-cssom-view-1-20160317/#enumdef-scrollbehavior
CSS で
CSS で指定することも出来ますと言ってもスクロールさせる処理自体は JavaScript で行うので スクロールの挙動だけを設定できます
html {
scroll-behavior: smooth;
}
これで html をスクロールさせると smooth scroll になります
document.documentElement.scrollTop = 200
document.documentElement.scrollTo({top: 400})
オブジェクトで指定する方法なら あまり大差ないですが 基本挙動を設定しておけるので指定漏れで挙動の統一性がなくなることを防げます
また scrollTop プロパティを直接書き換える方法でもスクロールの挙動を変えられます