<body>
<div class="texts">
<p>スクロール量:<span class="js-scrollY"></span></p>
<p>requestAnimationFrame</p>
<div class="box js-box"></div>
</div>
</body>
body {
height: 5000px;
margin: 0 20px;
position: relative;
.texts {
width: calc(100% - 40px);
position: fixed;
top: 0;
left: 50%;
transform: translateX(-50%);
}
.box {
width: 0;
height: 50px;
background-color: #333;
border: 2px solid #333;
box-shadow: inset 0 0 0 1px #fff;
}
}
View Compiled
let pageYOffset;
let boxWidth;
let bodyClientHeight = document.body.clientHeight;
let windowInnerHeight = window.innerHeight;
let scrollHeight = bodyClientHeight - windowInnerHeight;
const target = document.querySelector(".js-scrollY");
const targetBox = document.querySelector(".js-box");
const scrollFn = () => {
pageYOffset = window.pageYOffset;
boxWidth = (pageYOffset / scrollHeight) * 100;
target.innerText = pageYOffset;
targetBox.style.width = boxWidth + "%";
window.requestAnimationFrame(scrollFn);
};
scrollFn();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.