方法-スムーズスクロール
CSSを使用してスムーズなスクロール効果を作成する方法を学びます。
スムーズなスクロール
セクション1
リンクをクリックして、「スムーズな」スクロール効果を確認してください。
[私]をクリックして、下のセクション2までスムーズにスクロールします注:スムーズなスクロールを削除するには、scroll-behaviorプロパティを削除してください。
スムーズなスクロール
<html>要素に追加scroll-behavior: smooth
して、ページ全体をスムーズにスクロールできるようにします(注:特定の要素/スクロールコンテナーに追加することもできます)。
例
html {
scroll-behavior: smooth;
}
ブラウザのサポート
表の数字は、scroll-behaviorプロパティを完全にサポートする最初のブラウザバージョンを示しています。
Property | |||||
---|---|---|---|---|---|
scroll-behavior | 61.0 | 79.0 | 36.0 | 14.0 | 48.0 |
クロスブラウザソリューション
プロパティをサポートしていないブラウザの場合、JavaScriptまたはjQueryscroll-behavior
などのJavaScriptライブラリを使用して、すべてのブラウザで機能するソリューションを作成できます。
例
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all
links
$("a").on('click', function(event) {
// Make sure this.hash
has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
//
Store hash
var hash = this.hash;
// Using jQuery's animate() method
to add smooth page scroll
// The optional number (800) specifies the number
of milliseconds it takes to scroll to the specified area
$('html,
body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
ヒント:スクロール動作プロパティの詳細については、CSSリファレンス:CSSスクロール動作プロパティをご覧ください。