概要
このサイトのヘッダーでも実装している、スクロールされている割合をページに表示させるJavaScriptを実装します。

ソース
<div class="scroll-pos">
<div class="bar"></div>
</div>
if( !window.scrollTop ) {
window.scrollTop = ()=>{
return document.documentElement.scrollTop || document.body.scrollTop;
}
}
function setScrollPos(){
let $bar = document.querySelector('.scroll-pos .bar');
let onscroll = ()=>{
let $body = document.getElementsByTagName('body')[0];
let per = Math.round(window.scrollTop()/($body.offsetHeight - document.documentElement.clientHeight) * 100);
$bar.style.width = `${ per }%`;
};
window.addEventListener('scroll',onscroll,false);
}
setScrollPos();
.scroll-pos {
height: 5px;
background-color: #999;
}
.scroll-pos .bar {
-webkit-transition: all 300ms cubic-bezier(0.165, 0.84, 0.44, 1);
transition: all 300ms cubic-bezier(0.165, 0.84, 0.44, 1);
width: 0;
height: 5px;
background-color: #000;
}
解説
if( !window.scrollTop ) {
window.scrollTop = ()=>{
return document.documentElement.scrollTop || document.body.scrollTop;
}
}
スクロール位置をwindow.scrollTop()で取得できるようにしています。
let $bar = document.querySelector('.scroll-pos .bar');
要素 class=”bar” をスクロール割合によって変化させます。
window.addEventListener('scroll',onscroll,false);
スクロールイベントが発生するごとに関数「onscroll」を呼び出します。
let onscroll = ()=>{
let $body = document.getElementsByTagName('body')[0];
let per = Math.round(window.scrollTop()/($body.offsetHeight - document.documentElement.clientHeight) * 100);
$bar.style.width = `${ per }%`;
};
スクロール割合を求める数式は下記になります。
( スクロール位置 / (bodyの高さ – ブラウザの高さ) ) x 100
(bodyの高さ – ブラウザの高さ) しているのは一番下までスクロールした時、ブラウザ表示されている部分があるので、ページ全体の高さからブラウザで表示されている部分の高さを引いた値がスクロール可能領域になります。
最後に100掛けているのは( スクロール位置 / (bodyの高さ – ブラウザの高さ) )だと0〜1までなので100掛けてスタイルシートのwidthの%で使用できるようにしています。