ページトップへスクロール
ネイティブなJSで作成されたものを調べた結果、凝ったものも多くあった。
操作は単純なんだけど、イティブなJSで書くと結構コードが長くなり大変そうと言う印象。
なので最もお手軽パターンで決定。
/* HTML */
<div id="scrolltop"><span>⌃</span></div>
/* CSS */
#scrolltop {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
-ms-align-items: center;
align-items: center;
width: 50px;
height: 50px;
color: #fff;
background: rgba( 0, 0, 0, .7 );
line-height: 1;
cursor: pointer;
-webkit-border-radius: 100px;
border-radius: 100px;
position: fixed;
right: 1em;
bottom: 1em;
z-index: 999;
}
#scrolltop span {
display: block;
width: 100%;
text-align: center;
font-size: 20px;
}
とりあえずボタンを作成し、ページ内の最後の方に配置。
/* Javascript */
<script>
const scrolltop = document.getElementById('scrolltop');
scrolltop.addEventListener('click', function (e) {
e.preventDefault();
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
</script>
これでスムーズに動くはず。ただし速度など微調整などが出来ないのでその点は注意。
Safariでスムーズに動かないっ!
IEはさておいて、残念ながら「scrollToのbehavior」はSafariでは対応していない様子。
と言うことでPolyfill(ポリフィル)の出番です。スバラシイ。
下記よりダウンロードして「smoothscroll.js」を読み込むだけでOKだ。